2 条题解
-
0
- 更简单的方法,考虑如下 个事实
- 买股票,你手里的钱就会变少(因为你要花钱买股票嘛)
- 买股票,你手里的钱就会变多
- :表示前 天,买完股票 后,手里的钱的最大值
- :表示前 天,卖完股票 后,手里的钱的最大值
- 对于 有:
- 对于 有:
- 由于 和 只与 有关
- 因此,我们可以只用两个变量 和
#include <bits/stdc++.h> using namespace std; int maxProfit(vector<int>& a) { int n = a.size(), inf = 1000000000; // buy: 买完股票后手里的钱, 初始没买过股票, 所以 buy 是 -inf // sell: 卖完股票后手里的钱, 初始没有股票, 所以 sell 是 0 int buy = -inf, sell = 0; for (int i = 0; i < n; i++) { // 买股票, 手里的钱会变少 buy = max(buy, 0 - a[i]); // max(啥也不干, 买股票) // 卖股票, 手里的钱会变多 sell = max(sell, buy + a[i]); // max(啥也不干, 卖股票) } return sell; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; cout << maxProfit(a) << '\n'; return 0; } - 更简单的方法,考虑如下 个事实
-
0
- 假设我在第 天买入了股票
- 我当然要在后面价格最高的一天卖掉
#include <bits/stdc++.h> using namespace std; int maxProfit(vector<int>& p) { int n = p.size(); vector<int> f(n); f[n - 1] = p[n - 1]; for (int i = n - 2; i >= 0; i--) f[i] = max(p[i], f[i + 1]); int ans = 0; for (int i = 0; i < n - 1; i++) { ans = max(ans, max(0, f[i + 1] - p[i])); } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; vector<int> p(n); for (int i = 0; i < n; i++) cin >> p[i]; cout << maxProfit(p) << '\n'; return 0; }
- 1
信息
- ID
- 168
- 时间
- 100ms
- 内存
- 32MiB
- 难度
- 2
- 标签
- 递交数
- 55
- 已通过
- 36
- 上传者