动态规划 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
class Solution {
public int maxProfit(int[] prices) {
int max=0,min=99999;
for(int i=0;i<prices.length;i++){
max=Math.max(max,prices[i]-min);
min=Math.min(min,prices[i]);
}
return max;
}
}
暴力:
class Solution {
public int maxProfit(int[] prices) {
int max=0;
for(int i=0;i<prices.length-1;i++){
for(int j=i+1;j<prices.length;j++){
max=Math.max(max,prices[j]-prices[i]);
}
}
return max;
}
}
解题思路:只要今天比昨天价格高,即买入股票。
class Solution {
public int maxProfit(int[] prices) {
int res=0;
for(int i=1;i<prices.length;i++){
if(prices[i]-prices[i-1]>0)
res+=prices[i]-prices[i-1];
}
return res;
}
}