LeetCode#122. Best Time to Buy and Sell Stock II

  • Question: Given an array, the i-th element in the array represents the price of the stock on the i-th day. Under the specified game rules, find the maximum profit that the player can get from buying and selling this stock. The rules of the game are as follows: Players can make multiple buy and sell transactions, but they must sell their stocks before they can continue to buy.
  • Difficulty: Easy
  • Idea: Suppose the player buys the stock on the ith day and sells it on the jth day, then there are two situations:
    1. There is the kth day, i<k<jand prices[k]>prices[j], that is to say, the player bought on the ith day The stock should be sold on the kth day
    2. There is the kth day, i<j<kand prices[k]>prices[j], which means that it is not suitable to sell on the jth day, so there will be higher prices later.
    Traverse the array from back to front, if prices[i+1] > prices[i] are encountered, calculate the difference between prices[i+1] and prices[i] and accumulate it as the returned result.
    This approach can solve the two cases listed above.
  • Code:
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty() || prices.size() <= 1){
            return 0;
        }
        int len = prices.size();
        int result = 0;
        for(int i = len-1; i > 0; i--){
            if(prices[i] > prices[i-1]){
                result += prices[i] - prices[i-1];
            }
        }
        return result;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606692&siteId=291194637