Best Time to Buy and Sell Stock III - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Sunday, 16 August 2020

Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III


Best Time to Buy and Sell Stock III

Say 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 (i.e., you must sell the stock before you buy again).

Input: [3,3,5,0,0,3,1,4]
Output: 6
Input: [1,2,3,4,5]
Output: 4
Input: [7,6,4,3,1]
Output: 0

class Solution {

public:

    int maxProfit(vector<int>& prices) 

    {

          int debit_t1 = INT_MIN, credit_t1 = 0;

        int debit_t2 = INT_MIN, credit_t2 = 0;

        for(int i = 0; i < prices.size(); ++i){

            debit_t1 = max(debit_t1, -prices[i]);

            credit_t1 = max(credit_t1, debit_t1 + prices[i]);

            debit_t2 = max(debit_t2, credit_t1 - prices[i]);

            credit_t2 = max(credit_t2, debit_t2 + prices[i]);

        }

        return credit_t2;

    }

};