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 (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.
方法是直接找数组中递增序列的位置,因此多开了一个数组记录递增序列出现的初始位置,最后相加就好。代码如下:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n <= 1:
return 0
output = 0
a = [0] * n
for i in range(n-1):
if(prices[i] < prices[i+1]):
a[i] = 1
i = 0
while(i <= n-2):
low = 0
high = 0
if a[i] == 1:
low = prices[i]
high = prices[i+1]
while(a[i+1] == 1):
i = i+1
high = prices[i+1]
output = output + (high-low)
i = i + 1
return output
途中遇到的问题是,我发现python的range迭代器和for还是有区别的,比如i++的操作循环一遍就没用了。其实也可以直接离散的两两减,不用看成序列,结果不变只是操作麻烦而已。
速度beat 95%+
其他答案:
1.很有意思的一行代码,用zip用得很开心:
def maxProfit(self, prices):
return sum(y-x for x, y in zip(prices[:-1], prices[1:]) if y > x)
2.动态规划,虽然代码差不多,但是想法不同啊
设置走的路为天数 即 n,每天的状态转移方程为:
dp[i] = dp[i-1] if prices[i]<=prices[i-1] else dp[i-1]+(prices[i]-prices[i-1])
代码为:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# dp[i] = dp[i-1] if prices[i]<=prices[i-1] else dp[i-1]+(prices[i]-prices[i-1])
res = 0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
res += (prices[i]-prices[i-1])
return res