【Leetcode】122. Best Time to Buy and Sell Stock II买卖股票的最佳时机 II

  1. Best Time to Buy and Sell Stock II
    买卖股票的最佳时机 II买卖股票的最佳时机 II
    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).
[大意]给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)

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.

思路】1.贪心算法,判断某一小段的最高点,即在这部分利益最大。最终要求的利益最大,就是各部分最大利益之和。
2.这个方法是solution的,代码很简单,原理看下图,等效于只要后一天的大于前一天就可以买入卖出。
注:此解法不是说从第3天买入,第4天卖出,然后第4天买入第5天卖出......。这里的意思是这样的算得的利益
数值上等于 第3天买入,第6天卖出。

【Leetcode】122. Best Time to Buy and Sell Stock II买卖股票的最佳时机 II

代码1:
class Solution {
public:
    int maxProfit(vector<int>& prices) {
       int max=0,p=0,profit;        
        int i=0;
               for(int j=1;j<prices.size();j++){
                   profit=prices[j]-prices[i];
                       if(max>profit){
                           i=j;                         
                          p+=max;   
                           max=0;
                       }
                       else
                       {max=profit;
                        if(j==prices.size()-1)p+=max;
                       }                                       
               }
        return p;
    }
};

代码2:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        if(prices.size() <= 1) return 0;
        for(int i =1;i < prices.size();i++)
        {
           if (prices[i] > prices[i-1])
               {        
                   profit+=prices[i] - prices[i-1];
               }
            
        }
            
       return profit; 
    }
};