You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [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. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
A:
------------------3 rd pass -----------------
--就是很简单的一遍过即可---------不知道为什么,当时非要那么麻烦-----------------------------------------
class Solution {public:int maxProfit(vector<int>& prices) {int res = 0;int minBefore = prices[0];for(int i = 1; i<prices.size(); i++){res = max(res, prices[i] - minBefore);minBefore = min(minBefore, prices[i]);}return res;}};
就是CLRS上的,divide and conquer 问题。
第一遍做的,有点儿问题。( 虽然也pass了)
例如: 上来直接设 leftMax =0 是不对的。 有可能很小。 因为,对于cross的, 就是假定了, 左右,都必须含有。因此,需要先设为: 负无穷 ( CLRS上也是这样的)
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices!= null && prices.length<=1){
            return 0;
        }
        int[] change = new int[prices.length];
        for(int i =0; i<prices.length-1;i++){
            change[i] = prices[i+1] - prices[i];
        }
        return maxChange(change, 0 ,change.length-1);
    }
    //divide and conquers problem.
    public int maxChange(int[] change, int start, int end){
        if(start==end){
            return change[start];
        }
        else{
            int middle = (int)((start+end)/2);
            int leftMax = maxChange(change, start,middle);
            int rightMax = maxChange(change, middle+1, end);
            int crossMax = maxCross(change,start,middle,end);
            int maxProfit = (leftMax>rightMax)?leftMax:rightMax;
            if(crossMax > maxProfit){
                maxProfit = crossMax;
            }
            return maxProfit;
        }
        
    }
    private int maxCross(int[] change, int start, int middle, int end){
        //get max left part
        int leftMax = 0;
        int sum=0;
        for(int i =middle; i>=start; i--){
            sum += change[i];
            if(sum>leftMax){
                leftMax = sum;
            }
        }
        int rightMax = 0;
        sum = 0;
        for(int i =middle+1; i<=end; i++){
            sum +=change[i];
            if(sum>rightMax){
                rightMax=sum;
            }
        }
        return leftMax + rightMax;
    }
}
 
No comments:
Post a Comment