题目链接
https://leetcode.com/problems/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).
思路方法
思路一
额。。。虽说这题是贪心算法的应用,不过稍微还是简单了点。就怕想的太复杂,实际上只要能挣钱就买入卖出即可。
代码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
res = 0
for i in xrange(1, len(prices)):
if prices[i-1] < prices[i]:
res += prices[i] - prices[i-1]
return res
思路二
按照对题目的理解,对于类似[1,2,3,0]这样的序列,最正确的做法是“1元买入3元卖出”。而上面的解法感觉像是“1元买入2元卖出,2元买入3元卖出”,当然,结果是对的,而且其实上面的解法相当于代码优化。比较繁一点的解法是“先找局部最小,再找局部最大”这样的循环,代码如下:
代码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
res = 0
i = 0
while i < len(prices):
while i < len(prices)-1 and prices[i+1] <= prices[i]:
i += 1
j = i + 1
while j < len(prices)-1 and prices[j+1] >= prices[j]:
j += 1
res += prices[j] - prices[i] if j < len(prices) else 0
i = j + 1
return res
PS: 写错了或者写的不清楚请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52072136
时间: 2024-10-05 03:33:14