我最开始想把股价数组转成差价数组,这就成了53最大子序和问题了,看了题解发现只要找个最大值和最小值就行了,又做麻烦了。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int ans=0;
int x = 0;
vector<int>change = {0};
for (int i = 1; i < n; i++) {
change.push_back(prices[i]-prices[i-1]);
}
for (int i = 0; i < change.size(); i++) {
x = max(x + change[i], change[i]);
if (x > ans) {
ans = x;
}
}
return ans;
}
};
//找个最大值和最小值就行了
class Solution {
public:
int maxProfit(vector<int>& prices) {
int inf = 1e9;
int minprice = inf, maxprofit = 0;
for (int price : prices) {
maxprofit = max(maxprofit, price - minprice);
minprice = min(price, minprice);
}
return maxprofit;
}
};
int main() {
Solution test;
vector<int>prices = { 7,6,4,3,1 };
cout << test.maxProfit(prices);
}