今天刷Leetcode,遇到这样一个问题。
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.
转换一下,问题变成求数组中的前后两个数t1和t2,它们差值最大且t1<t2。
我的思路是这样的,从后往前,寻找当前子串的最大值,并计算最大值与当前价值prices[i]的差值,返回最大的差值。代码实现如下:
public int maxProfit(int[] prices) {
if(prices.length==0||prices.length==1) return 0;
int length=prices.length;
int maxPro=0;
int maxSale=prices[length-1];
for (int i = length-2; i >=0; i--) {
if(prices[i]>maxSale)
maxSale=prices[i];
if(maxSale-prices[i]>maxPro)
maxPro=maxSale-prices[i];
}
return maxPro;
}
提交成功以后发现这题的其他解法,用了Kadane's Algorithm,方法如下:
public int maxProfit(int[] prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.length; i++) {
maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar;
}
这个方法借鉴了Kadane算法的思想。
Kadane算法具体详情可以参照这篇博客:
http://www.linkedin.com/pulse/kadanes-algorithm-mustafa-bedir-tapkan
这里只贴一张图:
这个方法跟动态规划类似,用于寻找具有最大和的子数列,基于两个前提:
Kadane says that in each iteration we have only two options to get the max subarray:
- It can be only itself
- It can be itself combined with the maximum subarray that previous index has.
伪码如下:
kadane(Array){
generalMaximum = currentMaximum = Array[0]
for (i = 1 until n) {
currentMaximum = maximum of(Array[i], currentMaximum + Array[i]);
if(currentMaximum >= generalMaximum) generalMaximum = currentMaximum;
}
return generalMaximum;
}