"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Cracking the LeetCode . Best Time to Buy and Sell Stock II

Cracking the LeetCode . Best Time to Buy and Sell Stock II

Published on 2024-08-05
Browse:347

In my ongoing quest to sharpen my LeetCode skills, I tackled the "Best Time to Buy and Sell Stock II" problem. This challenge is a follow-up to the classic "Best Time to Buy and Sell Stock II" problem (LeetCode 121) but with a crucial difference: *you can execute multiple transactions to maximize profit.
*

A Visual Approach

Before diving into code, I found it incredibly helpful to visualize the problem on a whiteboard. This allowed me to break down the problem into smaller, more manageable steps.

Cracking the LeetCode . Best Time to Buy and Sell Stock II

The Greedy Approach

Given the flexibility to make unlimited transactions, a greedy approach seemed promising. The core idea is simple: whenever the price of a stock increases compared to the previous day, we consider it a potential profit opportunity. By adding up all these price differences, we effectively calculate the maximum profit.

Python Implementation

Here's the Python code that implements this greedy strategy:

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

        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                profit =prices[i] - prices[i-1]

        return profit

JavaScript Implementation

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var profit = 0;
    for (var i = 1; i  prices[i-1])
    {
        profit  = Number(prices[i] - prices[i-1])
    }
    }

    return profit
};

Time and Space Complexity

  • The time complexity of this approach is O(N) where N = length of array.
  • The space complexity is N(1) as we are comparing in place.
Release Statement This article is reproduced at: https://dev.to/this-is-learning/cracking-the-leetcode-122-best-time-to-buy-and-sell-stock-ii-17k5?1If there is any infringement, please Contact [email protected] to delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3