122 Best Time to Buy and Sell Stock II 買賣股票的最佳時(shí)機(jī) 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).
Example:
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.
題目描述:
給定一個(gè)數(shù)組祭务,它的第 i 個(gè)元素是一支給定股票第 i 天的價(jià)格蛇更。
設(shè)計(jì)一個(gè)算法來計(jì)算你所能獲取的最大利潤(rùn)石咬。你可以盡可能地完成更多的交易(多次買賣一支股票)。
注意:你不能同時(shí)參與多筆交易(你必須在再次購(gòu)買前出售掉之前的股票)地消。
示例:
示例 1:
輸入: [7,1,5,3,6,4]
輸出: 7
解釋: 在第 2 天(股票價(jià)格 = 1)的時(shí)候買入章钾,在第 3 天(股票價(jià)格 = 5)的時(shí)候賣出, 這筆交易所能獲得利潤(rùn) = 5-1 = 4 吕世。
隨后,在第 4 天(股票價(jià)格 = 3)的時(shí)候買入都许,在第 5 天(股票價(jià)格 = 6)的時(shí)候賣出, 這筆交易所能獲得利潤(rùn) = 6-3 = 3 稻薇。
示例 2:
輸入: [1,2,3,4,5]
輸出: 4
解釋: 在第 1 天(股票價(jià)格 = 1)的時(shí)候買入,在第 5 天 (股票價(jià)格 = 5)的時(shí)候賣出, 這筆交易所能獲得利潤(rùn) = 5-1 = 4 胶征。
注意你不能在第 1 天和第 2 天接連購(gòu)買股票塞椎,之后再將它們賣出。
因?yàn)檫@樣屬于同時(shí)參與了多筆交易,你必須在再次購(gòu)買前出售掉之前的股票。
示例 3:
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤(rùn)為 0哈扮。
思路:
遍歷數(shù)組時(shí), 找到后面的數(shù)字比前面的大的, 就加上兩者的差值
即找到每一段連續(xù)遞增數(shù)列
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int result = 0;
for (int i = 1; i < prices.size(); i++) if (prices[i] > prices[i - 1]) result += prices[i] - prices[i - 1];
return result;
}
};
Java:
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) if (prices[i] > prices[i - 1]) result += prices[i] - prices[i - 1];
return result;
}
}
Python:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
return sum(y - x for x, y in zip(prices, prices[1:]) if y > x)