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).
给出一个数组,数组里的第i个元素是股票在第i天的价格,同时最多只能持有一支股票,不可同天买进卖出,返回最大利润。
重点在于解题思路,算出每天的差价,正数相加为最大利润。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:return 0
p_dlist = []
for i in range(1,len(prices)):
p_dlist.append(prices[i]-prices[i-1])
sum = 0
for i in range(len(p_dlist)):
if p_dlist[i] > 0:
sum+=p_dlist[i]
return sum
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:return 0
p_dlist = []
for i in range(1,len(prices)):
p_dlist.append(prices[i]-prices[i-1])
sum = 0
for i in range(len(p_dlist)):
if p_dlist[i] > 0:
sum+=p_dlist[i]
return sum
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:return 0
if len(prices) == 2:
if prices[1] > prices[0]:return prices[1]-prices[0]
else:return 0
buylist = []
selllist = []
for i in range(1,len(prices)-1):
if prices[i]>prices[i+1]&prices[i-1]<prices[i]:
selllist.append(i)
if prices[i]<prices[i+1]&prices[i-1]>pricse[i]:
buylist.append(i)
if len(buylist)>0:
first = buylist[0]
for j in range(first):
if prices[j] < prices[buylist[0]]:
buylist[0] = j
else:buylist.append(0)
if len(selllist)>0:
last = selllist[-1]
for k in range(last,len(prices)):
if prices[k] > prices[selllist[-1]]:
selllist[-1] = k
else:selllist.append(len(prices)-1)
if selllist[0] > buylist[0]:
del selllist[0]
if buylist[-1] > buylist[-1]:
del buylist[-1]
sum = 0
for num in range(len(buylist)):
sum += prices[selllist[num]] - prices[buylist[num]]
return sum