• 股神(dp或贪心)


    Description

    2020 年 Quasrain 通过炒股赚了一些钱,但是 2021 年又亏了回去。
    站在天台上的 Quasrain 开始幻想一个美好世界。
    在那个世界 Quasrain 可以预知股票未来 n天的价格,股票每天的涨跌都不会超过 10%。
    在第 0 天 Quasrain 拥有一单位金币,股票的价格是一单位金币,
    当天 Quasrain 可以选择是否将金币兑换为股票。
    
    现在他想知道,n天之后他最多能拥有多少金币。

    Input

    第一行一个整数 n(1<=n<=500)。
    之后一行 n 个小数 a_i,表示之后 n 天每天股票的价格。

    Output

    输出一行一个小数表示答案,答案保留两位小数。

    Sample Input

    5
    0.92 0.88 0.90 0.93 0.88

    Sample Output

    1.06

    思路:

    dp:

    由于数据比较小,我们可以用dp,设d【i】为当前能获得最大现金,p[i]为当前能获得最大股票。

    #define _CRT_SECURE_NO_WARNINGS 
    #include
    #include
    #include
    #include
    #include<ctime>
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    using namespace std;
    typedef long long LL;
    typedef unsigned long long ULL;
    const int N = 1000;
    double d[N], p[N], a[N], ma;//d能获得最大现金,p是能获得最大股票
    int n;
    int main() {
        cin >> n;
        for (int i = 1; i <= n; i++) cin >> a[i];
        a[0] = 1;
        d[0] = 1;
        p[0] = 1;
        ma = d[0];
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j < i; j++)
            {
                p[i] = max(p[i], d[j] / a[i]);
                d[i] = max(d[i], p[j] * a[i]);
            }
            ma = max(d[i], ma);
        }
        printf("%.2f", ma);
        return 0;
    }

    贪心:

    对于a[i]

    a[i]

    a[i]>a[i+1],拿的是现金,不买。

    a[i]>a[i+1],拿的是股票,在这点卖,可以获得当前最大现金。

    代码:

    #define _CRT_SECURE_NO_WARNINGS 
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    using namespace std;
    typedef long long LL;
    typedef unsigned long long ULL;
    const int N = 1000;
    double  x, a[N],f=2;//当前为现金f=-1,若为股票f=1;
    int n;
    int main() {
        cin >> n;
        for (int i = 1; i <= n; i++) cin >> a[i];
        a[0] = 1;
        x = a[0];
        for (int i = 0; i <= n; i++)
        {
            if (a[i] < a[i + 1] && f !=1)
            {
                x = x / a[i];
                f = 1;

            }
            else if (a[i] > a[i + 1] && f != -1)
            {
                x = x * a[i];
                f = -1;
            }
        }
        printf("%.2f\n", x);
        return 0;
    }

  • 相关阅读:
    在 Git Bash 中调整字体大小,可以按照以下步骤进行操作,注意这里是linux虚拟机,命令都是Linux方式的
    将 BA、DevOps 和 QA 与云测试同步
    Java之@Autowired再分析
    Mqtt入门:在线调试连接阿里云
    Android之CompletableFuture一异步编程常用方法
    进程的通信 - 剪切板
    【leetcode】获取生成数组中的最大值 c++
    CSS简介
    再看tomcat的体会
    1-字典树-实现 Trie (前缀树)
  • 原文地址:https://blog.csdn.net/yusen_123/article/details/133976739