MaxStock

Run Settings
LanguageJavaScript
Language Version
Run Command
/* This is my pure JavaScript solution that i would implement with similar logic in REACT. We take the stocks as Array, At each day we try to buy stock We only buy stock if buying stock is profitable aka non negative return value. for each value we calculate maximum profit and keep track of the highest max profit using profit_max when for loop is finished we return maxProfit. this is a O(n^2) soln as we are iterating the array with two pointers to check for each day when we have max profit. */ function maxProfit( price, start, end) { if (end <= start) return 0; let profit_max = 0; for (let i = start; i < end; i++) { for (let j = i + 1; j <= end; j++) { if (price[j] > price[i]) { let curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); profit_max = Math.max(profit_max, curr_profit); } } } return profit_max; } let price = [ 4, 2, 3, 9, 4, 6, 7]; let n = price.length; console.log(maxProfit(price, 0, n - 1));
Editor Settings
Theme
Key bindings
Full width
Lines