Best Timeto Buyand Sell Stock I I Algorithm

The Best Time to Buy and Sell Stock II Algorithm is an optimization problem that aims to maximize the profit gained from buying and selling stocks, given an array of prices for each day. The algorithm allows one to perform multiple transactions, meaning that one can buy and sell stocks as many times as desired, but one must sell the stock before buying again. This problem serves as a classic example of dynamic programming and greedy algorithms, as it involves finding an optimal solution by breaking down the problem into smaller sub-problems and making the best choice at each step. The algorithm works by iterating through the given array of prices and comparing the price of a stock on a given day to the price on the following day. If the price on the following day is higher than the current day, the difference in prices represents a profit that can be made by buying on the current day and selling on the following day. By accumulating these profits, the algorithm computes the maximum possible profit that can be achieved. In essence, this algorithm operates on the principle of exploiting local optima to achieve a global optimum solution, as it greedily selects the local profits that can be made from transactions, ultimately leading to the maximum overall profit.
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        
        if (prices.empty()) return 0;

        int maxprofit = 0;
        int minvalue = INFS;
        for (size_t i = 0; i < prices.size(); i++) {
            minvalue = min(prices[i], minvalue);
            int profit = prices[i] - minvalue;
            if (profit > 0) {
                maxprofit += profit;
                minvalue = prices[i];
            }
        }
        return maxprofit;
    }
    //
    // firstly I thought this is a dynamic programming problem
    // but unfortunately, TLE in O(n^2)
    // It's a greed problem in O(n)
    //
    int maxProfit2(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.empty()) return 0;

        vector<int> dp(prices.size());
        dp[0] = 0;
        for (size_t i = 1; i < prices.size(); i++) {
            int maxvalue = prices[i];
            int maxprofit = 0;
            for (int j = i-1; j >= 0; j--) {
                maxvalue = max(maxvalue, prices[j]);
                maxprofit = max(maxprofit, maxvalue - prices[j]);
                dp[i] = max(dp[i], dp[j] + maxprofit);
            }
        }
        return dp[prices.size()-1];
    }
private:
    static const int INFS = 0x3FFFFFFF;
};

LANGUAGE:

DARK MODE: