121. Best Time to Buy and Sell Stock
比较熟悉的股票问题,动态规划典型。
这是第一道,比较简单。
用的思路是局部变量+全局变量。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length < 1) return 0;
int[] dp = new int[prices.length];
dp[0] = 0;
int res = 0;
for(int n = 1; n < prices.length;n++)
{
// compare to 0 actaully means check
// to see if current is a temp lowest value
// if it is, we re-calculate from current postion
// max profit before this position is already sotred
// in variable RES
dp[n] = Math.max(dp[n-1] - prices[n-1] + prices[n],0);
res = Math.max(res,dp[n]);
}
return res;
}
}
关键就是:
dp[n] = Math.max(dp[n-1] - prices[n-1] + prices[n],0);
原理是,假如昨天不卖,今天卖,那么收益是多少。
昨天的收益 - 昨天卖的收益(因为昨天不卖了)+今天的收益(今天卖)。
其实正确容易理解的做法是:
dp[n] = Math.max(dp[n-1] - prices[n-1] + prices[n];
if(dp[n] < 0)
{
dp[n] = 0; //今天买,今天卖
}
else
{
res = Math.max(res,dp[n]);
}
和0比较大小是为了找出局部最小值,比0小就说明:
此时卖,不管之前什么时候买,都是亏的,因为此时的价格非常低,所以我们不管之前了(之前的最大收益已经计算并通过RES保留了),今天买,今天卖,就是dp[n] = 0;
最后的RES是很多局部最大值中,最大的那个。
这个题,只能说code ganker局部、全局的思路很经典,也很他妈难想出来。
算3刷了吧。。
忘了原来那个思路,就正常做的。
今天的收入 = 昨天收入 - 昨天的价钱 + 今天的价钱
今天的收入小于0,干脆就不做生意了。。
更新最大收入。。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int[] local = new int[prices.length]; //sell on day n
int max = 0;
local[0] = 0;
for(int i = 1; i < prices.length; i++){
local[i] = local[i-1] - prices[i-1] + prices[i];
if(local[i] < 0) local[i] = 0;
max = Math.max(max,local[i]);
}
return max;
}
}
然后有个变量记录局部最大就行了,LOCAL不用是ARRAY。