Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
题目:最多一次买卖
思路:动规迭代,每天比较‘历史最大收益’和(当前价-历史最小价),然后比较‘历史最小价’和‘当前价’来更新‘历史最小价’
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) return 0;
int curMin=prices[0], maxBen=0;
for(int i = 1; i< prices.length; i++){
maxBen = Math.max(maxBen, prices[i]-curMin);
curMin = Math.min(curMin, prices[i]);
}
return maxBen;
}
}
题目:无限多次买卖
思路:贪心,凡是有收益就卖了,再从新找‘最小价’;如果当前没收益,则更新‘最小价’。
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) return 0;
int sumPro=0, minPri=prices[0];
for(int i=1; i<prices.length; i++){
if(prices[i]>minPri) {
sumPro+=prices[i]-minPri;
minPri=prices[i];
}else{
minPri=prices[i];
}
}
return sumPro;
}
}
题目:最多卖2次
思路:正反两次扫描,分别找到每天前后的最大利润,叠加
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) return 0;
int[] proFor = new int[prices.length];
int[] proBack = new int[prices.length];
int result = 0;
//forward
int curMin=prices[0], maxBen=0; proFor[0] = 0;
for(int i = 1; i< prices.length; i++){
maxBen = Math.max(maxBen, prices[i]-curMin);
proFor[i] = maxBen;
curMin = Math.min(curMin, prices[i]);
}
//backword
int curMax=prices[prices.length-1]; maxBen=0; proBack[prices.length-1] = 0;
for(int i = prices.length-2; i>=0 ; i--){
maxBen = Math.max(maxBen, curMax - prices[i]);
proBack[i] = maxBen;
curMax = Math.max(curMax, prices[i]);
}
for(int i=0; i<prices.length; i++){
result = Math.max(result,proFor[i]+proBack[i]);
}
return result;
}
题目:k次买卖
难题,没搞懂, 参考:
http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html
http://blog.csdn.net/linhuanmars/article/details/23236995
思路:第i天最多交易j次的最大利润dp[i][j]有三种情况:1.i天交易赔钱,所以不交易,则等于i-1天最多交易j次的最大利润dp[i-1][j],2.i天交易挣钱,a)连续挣dp[i-1][j]+diff,b) 间隔挣钱 dp[i-1][j-1]+diff