121 Best Time to Buy and Sell Stock


title: Best Time to Buy and Sell Stock
tags:
- best-time-to-buy-and-sell-stock
- No.121
- simple
- divide-conquer
- max-subarray


Description

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.

Corner Cases

  • decreasing
  • single [1]
  • binary [1,2]
  • negative case [-1, 1, 2]

Solutions

Divide and Conquer

Transfer the price array to difference array, which indicates the pure profit. Divide the array into 2 parts, solve each part independently and the case crossing the middle point.

The time complexity is O(n lg(n)), since the recursive relationship is T(n) = 2 T(\frac{n}{2}) + O(n):

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) {return 0;}
        boolean dec  = true;
        int[]   diff = new int[prices.length - 1];
        for (int i=0; i<prices.length-1; i++) {
            diff[i] = prices[i+1] - prices[i];
            dec = dec && (prices[i] > prices[i+1]);
        }
        // transfer to maximum subarray
        return (dec) ? 0 : divide_conquer(diff, 0, diff.length-1);
    }

    private int divide_conquer(int[] diff, int a, int b) {
        if (a  == b) {return diff[a];}
        int c  = (a + b)/2;
        int s1 = divide_conquer(diff, a, c);
        int s2 = divide_conquer(diff, c+1, b);
        int s3 = crossing(diff, a, b, c);
        int m  = (s1 > s2) ? s1 : s2;
        return (m > s3) ? m : s3;
    }

    private int crossing(int[] diff, int a, int b, int c) {
        int sum  = 0;
        int lsum = -2147483648;
        int rsum = -2147483648;

        for (int i=c; a<=i; i--) {
            sum = sum + diff[i];
            lsum = (sum > lsum) ? sum : lsum;
        }
        sum = 0;
        for (int j=c+1; j<=b; j++) {
            sum = sum + diff[j];
            rsum = (sum > rsum) ? sum : rsum;
        }

        return lsum + rsum;
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容