股神(dp或贪心)
最佳答案 问答题库468位专家为你答疑解惑
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;
}
99%的人还看了
相似问题
- 121. 买卖股票的最佳时机 --力扣 --JAVA
- 股票基础数据(二)
- 代码随想录算法训练营第四十九天| 123.买卖股票的最佳时机III 188.买卖股票的最佳时机IV
- 时序预测 | Python实现ConvLSTM卷积长短期记忆神经网络股票价格预测(Conv1D-LSTM)
- 代码随想录算法训练营第四十八天|121. 买卖股票的最佳时机 122.买卖股票的最佳时机II
- 机器学习股票大数据量化分析与预测系统 - python 计算机竞赛
- 动态规划30(Leetcode123买股票的最佳时机3)
- 动态规划29(Leetcode714买卖股票的最佳时期含手续费)
- Leetcode121买股票的最佳时机
- Leetcode122买股票的最佳时机2
猜你感兴趣
版权申明
本文"股神(dp或贪心)":http://eshow365.cn/6-21932-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!