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).
思路:
遍历整个数组,如果当前元素小于上个元素,那么证明我们不能在上个元素那一天买股票,那样会亏钱,如果当前元素大于上个元素,那么我们就把它和上个元素得的差值加入总和num中,比如【2,4,6,8,3,1,10】,我们会在第一天买入2,第四天卖出8,那么我们就赚了6,然后我们在第六天买入1,第七天卖出10,又赚了9,总共就赚了15
代码:
1 class Solution(object): 2 def maxProfit(self, prices): 3 """ 4 :type prices: List[int] 5 :rtype: int 6 """ 7 num = 0 8 if len(prices) <= 1: 9 return 0 10 prev = prices[0] 11 for i in range(1, len(prices)): 12 if prev < prices[i]: 13 num = num + prices[i] - prev 14 prev = prices[i] 15 return num

浙公网安备 33010602011771号