Best Time Buy and Sell Stock - LeetCode

265 阅读2分钟

Q****121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), 
profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy 
before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 10^5

解法及注释

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # pre-check
        if prices == None or len(prices) == 0:
            return 0
        
        # keep a minVal up to prices[i], and compare the profit against maxPnL
        minVal = max(prices)
        maxPnL = 0
        for i in range(len(prices)):
            if prices[i] < minVal:
                minVal = prices[i]
            elif prices[i] - minVal > maxPnL:
                maxPnL = prices[i] - minVal
        return maxPnL

Q****122. Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:

  • 1 <= prices.length <= 3 * 104
  • 0 <= prices[i] <= 10^4

解法及注释

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # pre-check
        if prices == None or len(prices) <= 1:
            return 0
        
        sum = prices[1] - prices[0] if prices[1] > prices[0] else 0
        for i in range(2, len(prices)):
            if prices[i] > prices[i-1]:
                sum += prices[i] - prices[i-1]
        return sum

Q****123. Best Time to Buy and Sell Stock III

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 10^5

解法及注释

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # pre-check
        if prices == None or len(prices) < 2:
            return 0
        
        buy1 = buy2 = -prices[0]
        profit1 = total = 0
        for price in prices:
            buy1 = max(buy1, -price)
            profit1 = max(profit1, buy1 + price)
            buy2 = max(buy2, profit1 + (-price))
            total = max(total, buy2 + price)
        return total

Q****188. Best Time to Buy and Sell Stock IV

You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.

Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

Constraints:

  • 1 <= k <= 100

  • 1 <= prices.length <= 1000

  • 0 <= prices[i] <= 1000

    class Solution { public int maxProfit(int k, int[] prices) { //pre-check if (k < 1 || k > 100 || prices == null || prices.length == 0 || prices.length > 1000) { return 0; }

        int[] cost = new int[k + 1];
        int[] profit = new int[k + 1];
        
        Arrays.fill(cost, Integer.MAX_VALUE);
    
        for(int price: prices) {
            for(int i = 0; i < k; i++) {
                cost[i + 1] = Math.min(cost[i + 1], price - profit[i]);
                profit[i + 1] = Math.max(profit[i + 1], price - cost[i + 1]);
            }
        }
    
        return profit[k];
    }
    

    }

Q****309. Best Time to Buy and Sell Stock with Cooldown

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]

Example 2:

Input: prices = [1]
Output: 0

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

解法及注释

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # pre-check
        if prices == None or len(prices) < 2:
            return 0
        
        buy = -prices[0]
        sell = 0
        cooldown = 0
        for i in range(len(prices)):
            tempBuy = max(buy, cooldown - prices[i])
            cooldown = sell
            sell = max(sell, buy + prices[i])
            buy = tempBuy
        return sell

Q****714. Best Time to Buy and Sell Stock with Transaction Fee

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Example 2:

Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6

Constraints:

  • 1 <= prices.length <= 5 * 104

  • 1 <= prices[i] <= 5 * 104

  • 0 <= fee <= 5 * 104

解法及注释

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        # pre-check
        if prices == None or len(prices) == 0:
            return 0
        
        buy = -prices[0]
        sell = 0
        for i in range(1, len(prices)):
            newBuy = max(buy, sell + (-prices[i]))
            newSell = max(sell, buy + prices[i] - fee)
            buy = newBuy
            sell = newSell
        return sell

作者:Richard2012
链接:juejin.cn/post/692564…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。