【题目】

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

【思路】
Kadane's Algorithm差值
*可能的困惑点,只能在一天买,另一天卖,为什么可以用i/i-1算临两天的(update 8.22)

b3 = a3 - a2
b4 = a4 - a3
b5 = a5 - a4
b6 = a6 - a5

所有中间项都将抵消

b3 + b4 + b5 + b6 = a6 - a2

a6 - a2 是所需的解决方案


【代码】
class Solution {
    public int maxProfit(int[] prices) {
        int cur=0;
        int sum=0;
        for(int i=1;i<prices.length;i++){
            cur+=prices[i]-prices[i-1];
            sum=Math.max(sum,cur);
            cur=cur>0?cur:0;
        }
        return sum;
    }
}

 

 

class Solution {
    public int maxProfit(int[] prices) {
        int cur=0;
        int sum=0;
        for(int i=1;i<prices.length;i++){
            cur+=prices[i]-prices[i-1];
            sum=Math.max(sum,cur);
            cur=cur>0?cur:0;
        }
        return sum;
    }
}

 posted on 2018-11-05 11:46  alau  阅读(122)  评论(0编辑  收藏  举报