LeetCode 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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析

可以交易多次的买卖股票问题

  • 条件:同一时间只能有一次正在进行的交易

代码

1
2
3
4
5
6
7
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))

点评

将 股票价格数组转换成一个当天的上涨数组,下跌的当天置为0,求得所有和就可以了