0. 链接
1. 题目
Say you have an array prices 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.
Constraints:
1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4
2. 思路1: 遍历找波峰波谷
- 记录buy_price, sell_price, max_profit
- 从左到右遍历,
- 遇到price比buy_price小的, 则更新buy_price, - 遇到price比sell_price大的, 则更新sell_price
- 当遇到price比上一个sell_price小, 说明上一个sell_price就是波峰, 此时进行一次结算 max_profit += sell_price - buy_price, 并重置buy_price=price, sell_price=None
- 时间复杂度: ```O(N)``
- 空间复杂度:
O(1)
3. 代码
# coding:utf8
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
buy_price = prices[0]
sell_price = None
max_profit = 0
for i in range(1, len(prices)):
price = prices[i]
if sell_price is None:
if price < buy_price:
buy_price = price
else:
sell_price = price
else:
if price < sell_price:
max_profit += sell_price - buy_price
buy_price = price
sell_price = None
else:
sell_price = price
if sell_price is not None:
max_profit += sell_price - buy_price
return max_profit
def my_test(solution, prices):
print('input: {}; output: {}'.format(prices, solution.maxProfit(prices)))
solution = Solution()
my_test(solution, [7, 1, 5, 3, 6, 4])
my_test(solution, [1, 2, 3, 4, 5])
my_test(solution, [7, 6, 4, 3, 1])
输出结果
input: [7, 1, 5, 3, 6, 4]; output: 7
input: [1, 2, 3, 4, 5]; output: 4
input: [7, 6, 4, 3, 1]; output: 0
4. 结果
5. 思路2: 积分法
- 求所有呈上升趋势的阶段的增量和
- 时间复杂度
O(N)
- 空间复杂度
O(1)
6. 代码
# coding:utf8
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
max_profit += prices[i] - prices[i - 1]
return max_profit
def my_test(solution, prices):
print('input: {}; output: {}'.format(prices, solution.maxProfit(prices)))
solution = Solution()
my_test(solution, [7, 1, 5, 3, 6, 4])
my_test(solution, [1, 2, 3, 4, 5])
my_test(solution, [7, 6, 4, 3, 1])
输出结果为
input: [7, 1, 5, 3, 6, 4]; output: 7
input: [1, 2, 3, 4, 5]; output: 4
input: [7, 6, 4, 3, 1]; output: 0