思路一、
双层循环 O(n^2),复杂度太高,不是一个好答案.
class Solution {
public:
int maxProfit(vector<int>& prices) {
//双指针的做法, 固定一侧
int maxn = 0;
for(int i = 0; i < prices.size(); i++) {
for(int j = prices.size() - 1; j > 0; j--) {
if(i > j) break;
if(maxn <= prices[j] - prices[i]) {
maxn = prices[j] - prices[i];
}
}
}
return maxn > 0 ? maxn : 0;
}
};
思路二、
O(n),动态规划算法,但是打败的人不多
class Solution {
public:
int maxn(int a, int b) {
return a > b ? a : b;
}
int maxProfit(vector<int>& prices) {
/** profits[i] = max{profits[i - 1], prices[i] - minPrice}
* profits[0] = -prices[0]
*/
vector<int> profits;
profits.resize(prices.size());
profits[0] = -1 * prices[0];
int minPrice = prices[0];
int maxxx = 0;
for(int i = 1; i < prices.size(); i++) {
minPrice = minPrice < prices[i - 1] ? minPrice : prices[i - 1];
profits[i] = maxn(profits[i - 1], prices[i] - minPrice);
if(maxxx < profits[i]) {
maxxx = profits[i];
}
}
return maxxx;
}
};