跳转至

122.Best Time to Buy and Sell Stock II

Tags: Easy Greedy

Links: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/


Say you have an array for which the i*th element is the price of a given stock on day *i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;

        for (size_t i = 1; i < prices.size(); ++i){
            if (prices[i] > prices[i - 1])
                profit += prices[i] - prices[i - 1];
        }

        return profit;
    }
};

最初的想法是和“最大M子段和”问题联系起来,显然这是两两配对的,那么可以令m = prices.size() / 2来计算,用一个数组来保留每次的结果,最后取最大的值就是结果。但是考虑如果数组有几千个元素,那么这种效率实在是太低了,会超时。

此题应该采取贪心的策略:

数组总可以被划分为一个个的区间,这个区间如果是单调上升的,那么肯定取首位差值,相应的此区间也可以被称为持股区间X

建立示性函数: $$ \chi_{\left[a_{i} a_{i + 1}\right]}=\left{\begin{array}{l}{1,\left[a_{i}, a_{i+1}\right] \subset X} \ {0,\left[a_{i}, a_{i+ 1}\right] \not \subset X}\end{array}\right. $$ 目标函数: $$ \max \sum_{i=1}^{n-1}\left(a_{i+1}-a_{i}\right) \cdot \chi_{\left[a_{i} a_{i+1}\right]} \ \sum_{i=1}^{n-1}\left(a_{i+1}-a_{i}\right) \cdot \chi_{\left[a_{i} a_{i+1 j}\right]}=\sum_{+} \Delta a \chi+\sum_{-} \Delta a \chi \leq \sum_{+} \Delta a \chi \leq \sum_{+} \Delta a $$ 其中\sum_{+} \Delta a\chi表示所有区间差为正数的区间差值总和。显然取到最优值(取等号)就是a_{i+1} - a_i \ge 0