DEV Community

Discussion on: Daily Challenge #228 - Best Profit in Single Sale

akhilpokle profile image
Akhil • Edited on

O(n) time and O(1) space: Kadane's algorithm

var maxProfit = function(prices) {
    let maxCurr = 0;
    let maxSale = 0;
    for(let i=1;i<prices.length;i++){
        maxCurr = Math.max(0,maxCurr += prices[i]-prices[i-1]);
        maxSale = Math.max(maxCurr,maxSale);
    return maxSale;

aminnairi profile image

Nice one, but there are some things that bother me in the code.

You could have replaced the var by a let or a const in the first line since you are using let later.

You can increase the speed execution of your algorithm by caching the length of the prices variables, which is not changing over the course of your iterations.

Your variable maxCurr lacks a variable declaration keyword: either let or const.

Also, you are using the maxCurr variable before even declaring it. That does not make sense.

I tried to run it but it threw some exceptions, did you run it on your local machine?

akhilpokle profile image
Akhil • Edited on

Thanks for pointing out, it's a typo. My bad. I have updated the code.