letecode [122] - Best Time to Buy and Sell Stock 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).
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.pre保存买入值,当prices[i]<pre时更新买入值(中间没有利润值);
3.当prices[i]>prices[i+1]时,说明产生了一次买入卖出,买入价为pre,卖出价为prices[i];更新pre为prices[i+1];
4.对prices[n-1]单独处理。
方法二:
参考官网解法,直接遍历数组,当prices[i]>prices[i-1],累加差值,即为利润和。时间复杂度和方法一一样是O(n),但不用保存当前最小买入值等。
代 码 C++:
方法一:
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n==0) return 0; int pre=prices[0],profit=0; for(int i=1;i<n-1;++i){ if(pre>prices[i]) pre = prices[i]; if(prices[i]>prices[i+1]){ if(prices[i]>pre) profit += prices[i] - pre; pre = prices[i+1]; ++i; } } if(prices[n-1]>pre) profit += prices[n-1] - pre; return profit; } };
方法二:
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n==0) return 0; int profit=0; for(int i=1;i<n;++i){ if(prices[i]>prices[i-1]) profit += prices[i]-prices[i-1]; } return profit; } };
运行结果:
方法一:执行用时 : 16 ms 内存消耗 : 9.5 MB
方法二:执行用时 : 12 ms 内存消耗 : 9.7 MB