Similar Problems

Similar Problems not available

Best Time To Buy And Sell Stock Ii - Leetcode Solution

LeetCode:  Best Time To Buy And Sell Stock Ii Leetcode Solution

Difficulty: Medium

Topics: greedy dynamic-programming array  

Problem Statement:

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).

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

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 = 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 = 4.

Example 3:

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

Solution:

We just need to find the valley (lowest point) and peak (highest point) in the given array of stock prices. We can simply traverse the array and keep a check for every increment in price. Whenever we encounter a point where the price is smaller than the previous one, we simply set Valley = current price and Peak = 0. Whenever we encounter a point where the price is greater than the previous one, we simply set Peak = current price and add (Peak - Valley) to our profit.

Algorithm:

  • Initialize the current price to the price of the first day
  • Initialize the maximum profit to 0
  • Iterate through the list of prices
    • If the current price is greater than the previous price, add the difference to the maximum profit
    • Update the current price
  • Return the maximum profit

Code:

class Solution: def maxProfit(self, prices: List[int]) -> int: currentPrice = prices[0] maxProfit = 0

    for i in range(1, len(prices)):
        if prices[i] > currentPrice:
            maxProfit += prices[i] - currentPrice
        currentPrice = prices[i]
        
    return maxProfit

Time complexity: O(n)

Space complexity: O(1)

Explanation:

We first initialize the current price to the price of the first day and the maximum profit to 0. We then iterate through the list of prices, starting from the second day, and check if the current price is greater than the previous price. If it is, we add the difference between the current price and the previous price to the maximum profit. We then update the current price. Finally, we return the maximum profit. This algorithm is of time complexity O(n) and space complexity O(1).

Best Time To Buy And Sell Stock Ii Solution Code

1