题目描述;
方法一(动态规划):
代码中第二个坐标的意思:0代表不持有股票,1表示持有股票
在第i天,不持有股票的最大利润是不低于持有股票的最大利润的。
对于第i天来说,如果是不持有股票的情况,无非是保持第i-1天不持有股票的状态或者第i天卖出,是取两者的最大值;如果是持有股票的情况,为保持第i-1天持有股票的情况或者第i天买进股票,也是取两者的最大值。
profit[0][0] = 0;
profit[0][1] = -prices[0];
如果第一天股价较低是适合买入的,要考虑在内。
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len < 2){
return 0;
}
int[][] profit = new int [len][2];
profit[0][0] = 0;
profit[0][1] = -prices[0];
for(int i = 1;i < len;i++){
profit[i][0] = Math.max(profit[i-1][0],profit[i-1][1]+prices[i]);
profit[i][1] = Math.max(profit[i-1][1],profit[i-1][0]-prices[i]);
}
return profit[len-1][0];
}
}
结果:
空间优化,不用数组直接用变量。(PS:三目表达式比Math.max()方法快了1ms左右,此代码用max耗时2ms)
代码:
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len < 2){
return 0;
}
int cash = 0,stock = -prices[0];
int preCash = cash,preStock = stock;
for(int i = 1;i < len;i++){
cash = preCash > preStock+prices[i] ? preCash : preStock+prices[i];
stock = preStock > preCash-prices[i] ? preStock : preCash - prices[i];
preCash = cash;
preStock = stock;
}
return cash;
}
}
结果:
方法二(贪心法):
贪心法求的是局部最优解,在某些问题中,经过一次次得来的局部最优解最后就是全局最优解。在此题中,只要今天的股价比昨天高,我就可以卖出。经过多次买卖,利润累加,就可以得到最大利润。(PS:现实中谁一定能说准股价的高低)
代码:
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len < 2){
return 0;
}
int everyProfit = 0,profit = 0;
for(int i = 1;i < len;i++){
everyProfit = prices[i] - prices[i-1];
if(everyProfit > 0){
profit += everyProfit;
}
}
return profit;
}
}
结果: