Best Time to Buy and Sell Stock with Transaction Fee LeetCode solution in JavaScript

1
/**
2
* @param {number[]} prices
3
* @param {number} fee
4
* @return {number}
5
*/
6
var maxProfit = function (prices, fee) {
7
let purchase = -1 * prices[0]; //If we purchase on 0th day
8
let sell = 0; //If we sell on 0th day
9
let prevPurchase;
10
for (let i = 1; i < prices.length; i++) {
11
prevPurchase = purchase;
12
purchase = Math.max(purchase, sell - prices[i]); //If we purchase on ith day
13
sell = Math.max(sell, prevPurchase + prices[i] - fee); //If we sell on ith day
14
}
15
return sell; //If must return the best price whenever we sold stock because then only we can be at max profit.
16
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0