题解 | #买卖股票的最好时机(二)#
买卖股票的最好时机(二)
https://www.nowcoder.com/practice/fbc5dad3e215457fb82a3ae688eb7281
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution{
public:
int solve (vector<int>& prices) {
int sell = 0, buy = 0;
sell = 0; //第0天卖股票的收益
buy = -prices[0]; //第0天买股票的收益
for (int i = 1; i < (int)prices.size(); ++i) {
buy = max(sell - prices[i], buy); //第i天买股票的最大收益
sell = max(sell, buy + prices[i]);//第i天卖股票的最大收益
}
return sell > 0 ? sell : 0;
}
};
int main() {
int n;
cin >> n;
vector<int> prices(n, 0);
for (int i = 0; i < n; ++i) {
cin >> prices[i];
}
Solution * s = new Solution();
int ret = s->solve(prices);
cout << ret << endl;
return 0;
}
#include<vector>
#include<algorithm>
using namespace std;
class Solution{
public:
int solve (vector<int>& prices) {
int sell = 0, buy = 0;
sell = 0; //第0天卖股票的收益
buy = -prices[0]; //第0天买股票的收益
for (int i = 1; i < (int)prices.size(); ++i) {
buy = max(sell - prices[i], buy); //第i天买股票的最大收益
sell = max(sell, buy + prices[i]);//第i天卖股票的最大收益
}
return sell > 0 ? sell : 0;
}
};
int main() {
int n;
cin >> n;
vector<int> prices(n, 0);
for (int i = 0; i < n; ++i) {
cin >> prices[i];
}
Solution * s = new Solution();
int ret = s->solve(prices);
cout << ret << endl;
return 0;
}