题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
题目:
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.
解题思路:
这题一看就是动态规划。
最基础的想法是,对于数组中的每一个元素,在下标大于它的元素中找到最大的一个元素,它们的差值就是该元素的最大利润。
这种想法的时间复杂度很高,对每一个元素都要求它之后的最大值。
换个角度思考,可以从数组尾部开始遍历元素,同样是找到最大值,进行比较,但是每向前推进一个元素,最大值的更新过程变得很简单,是老的最大值和刚遍历过的元素两者取最大值。再和当前元素求差值,得到当前元素的最大利润。
补充一下大神的解法,也很巧妙:
很容易感觉出来这是动态规划的题目,用“局部最优和全局最优解法”。
1. 思路是维护两个变量,一个是到目前为止最好的交易,另一个是在当前一天卖出的最佳交易(也就是局部最优)。
2. 递推式是:
local[i+1]=max(local[i]+prices[i+1]-price[i],0)
global[i+1]=max(local[i+1],global[i])。
3. 这样一次扫描就可以得到结果,时间复杂度是O(n)。而空间只需要两个变量,即O(1)。
代码实现:
自己的思路:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int max = prices[prices.length - 1];
int maxProfit = -1;
for(int i = prices.length - 2; i >= 0; i --) {
int localProfit = max - prices[i];
if(maxProfit < localProfit)
maxProfit = localProfit;
if(max < prices[i])
max = prices[i];
}
return maxProfit < 0 ? 0 : maxProfit;
}
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 2 ms
大神的思路:
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int local = 0;
int global = 0;
for(int i=0;i<prices.length-1;i++)
{
local = Math.max(local+prices[i+1]-prices[i],0);
global = Math.max(local, global);
}
return global;
}
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 3 ms