leetcode -- the best time to buy and sell stocks

122

Given an array whose ith element is the price of a given stock on the ith day.
Design an algorithm to calculate the maximum profit you can make. You can complete as many trades as you can (buying and selling a stock multiple times).

Note: You cannot participate in multiple trades at the same time (you must sell the previous shares before buying again).

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (stock price = 1), buy on day 3 (stock price = 5) Sell, this exchange can get profit = 5-1 = 4.
Then, by buying on day 4 (stock price = 3) and selling on day 5 (stock price = 6), the exchange earns a profit = 6-3 = 3.

Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (stock price = 1), sell on day 5 (stock price = 5) , the exchange can earn profit = 5-1 = 4 .
Note that you cannot buy stocks on Day 1 and Day 2 and sell them later.
Because this is part of multiple trades at the same time, you must sell the previous stock before buying it again.

Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no trade is completed, so the maximum profit is 0.

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        income, buy = 0, -1
        lenth = len(prices)
        for i in range(lenth):
            if i < lenth-1 and prices[i+1] > prices[i] and buy == -1:
                buy = prices[i]
            elif i > 0 and prices[i] < prices[i-1] and buy != -1:
                income = income + prices[i-1] - buy
                buy = prices[i]
            elif i == lenth - 1 and buy != -1:
                income = income + prices[i] - buy

        return income   

The logic is a little more complicated, but it can ensure that the purpose is achieved with the least operation. If you do not need to control the operand, the logic can be simpler

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        income, profit = 0, 0
        lenth = len(prices)
        for i in range(lenth-1):
            profit = prices[i+1] - prices[i]
            if  profit> 0:
                income += profit

        return income 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733224&siteId=291194637