DEV Community

codingpineapple
codingpineapple

Posted on

1 1

LeetCode 188. Best Time to Buy and Sell Stock IV (javascript solution)

Description:

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.

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

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n)

 var maxProfit = function(k, prices) {
    if(!prices.length) return 0;
    // Create dp arrays
    const even = Array(prices.length).fill(0)
    const odd = Array(prices.length).fill(0)

    for(let i = 1; i < k+1; i++) {
        let prevMax = -Infinity
        // Switch arrays to proper values when we are on an odd or even number
        const current = i % 2 === 0 ? even : odd;
        const prev = i % 2 === 0 ? odd : even;
        // Fill dp arrays with max profit on each day when making i amount of transactions
        for(let j = 1; j < prices.length; j++) {
            prevMax = Math.max(prevMax, prev[j-1] - prices[j-1])
            // current[j-1] means we will do nothing on the j day and take the max profit from the previous day
            // prices[j] + prevMax is the profit from gained on this day (prices[j]) and the max profit we could make from a previous transaction (prevMax)
            current[j] = Math.max(current[j-1], prices[j]+prevMax)
        }
    }
    // Current and prev change based on i. This chooses the correct curent array
    return k % 2 === 0 ? even[even.length-1] : odd[odd.length-1]
};

Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay