股神(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<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>
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+1]并且当前拿的是现金,我们买股票可以获得更大现金。

a[i]<a[i+1],拿的是股票,就到下一个点,在这点不卖。

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

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

代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>
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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值