Monday, November 25, 2013

LeetCode Problem : Best Time to Buy and Sell Stock III

Problem



ay you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Code

int mp(vector<int> &prices,int begin,int end) {
    int n = end - begin + 1;
    if(n < 1)
        return 0;
    vector<int> M(n);
    int max_sum = M[0] = prices[begin];
    for(int i = 1;i < n;++i){
        M[i] =  prices[begin + i];
        if(M[i - 1] > 0)
        M[i] += M[i - 1];
        if(max_sum < M[i])
        max_sum = M[i];
    }
    return (max_sum > 0 ? max_sum : 0);
}
int maxProfit(vector<int> &prices) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int n = prices.size();
    if(n < 2)
        return 0;
    for(int i = 0;i < n - 1;++i){
        prices[i] = (prices[i + 1] - prices[i]);
    }
    int k = 0,max_sum = INT_MIN;
    while(k < (n - 1)){
        int j = k;
        while(j < n - 1 && prices[j] <= 0)
            ++j;
        while(j < n - 1 && prices[j] >= 0)
            ++j;
        int p1 = mp(prices,0,j - 1);
        int p2 = mp(prices,j,n - 2);
        if(max_sum < (p1 + p2))
            max_sum = (p1 + p2);
        k = j;
    }
    return max_sum;
}

No comments:

Post a Comment