【LeetCode】122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock II

Description:
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 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).
Difficulty:Easy
相似题目:
简单版
升级版
Example:

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.

方法1:山谷和山顶

  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for(int i = 1; i < prices.size(); i ++){
            while(i < prices.size() && prices[i] <= prices[i-1])
                i++;
            int start = prices[i-1];
            while(i < prices.size() && prices[i] >= prices[i-1])
                i++;
            int end = prices[i-1];
            res += end - start;
        }
        return res;
    }
};

方法2:分波段,取上升

  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for(int i = 1; i < prices.size(); i ++){
            if(prices[i] > prices[i-1])
                res += prices[i] - prices[i-1];
        }
        return res;
    }
};

你可能感兴趣的:(基础算法)