122. Best Time to Buy and Sell Stock II@python
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.
原题地址: Best Time to Buy and Sell Stock II
难度: Easy
题意: 买卖股票,允许多次买卖,但不允许同一天即买入又卖出,返回最大利润
思路:
遍历数组, 计算当前一个数与前一个数的差值, 差值大于0,表明是利润
代码:
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) res = 0 for i in range(1, n): profit = prices[i] - prices[i-1] if profit > 0: res += profit return res
时间复杂度: O(n)
空间复杂度: O(1)

浙公网安备 33010602011771号