您的位置:首页 > 其它

leetcode122.[DP] Best Time to Buy and Sell Stock II

2016-03-24 14:56 369 查看
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).

思路:今天价格减去前一天价格,如果为正,则加进sum中

import sys
MAX_=sys.maxint
MIN_=-sys.maxint
class Solution(object):
def maxProfit(self, prices):
if not len(prices):
return 0
sum=0
prices.append(MIN_)
prices.insert(0,MAX_)
flag_pre=-1
flag_last=-1
for i in range(1,len(prices)-1):
if flag_pre==-1:
if prices[i]<prices[i+1] and prices[i]<=prices[i-1]:
flag_pre=prices[i]
if flag_pre!=-1:
if prices[i]>prices[i+1] and prices[i]>=prices[i-1]:
flag_last=prices[i]
if flag_pre!=-1 and flag_last!=-1:
sum=sum+flag_last-flag_pre
flag_pre=-1;flag_last=-1
if flag_pre!=-1 and flag_last!=-1:
sum=sum+flag_last-flag_pre
return sum


import sys
MAX_=sys.maxint
class Solution(object):
def maxProfit(self, prices):
if not len(prices):
return 0
sum=0
prices.insert(0,MAX_)
for i in range(1,len(prices)):
diff=prices[i]-prices[i-1]
if diff>=0:
sum=sum+diff
return sum
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: