buy-and-sell.js (951B)
1 //Find the best time to buy and sell a stock to maximize profits 2 //given a set of input times. To solve this you need to find 3 //the max difference. I did this by subtracting the min from every 4 //value higher than it to see if that is larger than the current max 5 //if it is then max = currentmax - currentmin. 6 //The time complexity of this code is O(n) where n is the length 7 //of the prices list. 8 //Runtime: 84ms Beats: 57.61% 9 //Memory: 51.2MB Beats: 91.18% 10 11 /** 12 * @param {number[]} prices 13 * @return {number} 14 */ 15 var maxProfit = function(prices) { 16 17 18 let return_val = 0; 19 let max = prices[0]; 20 let min = prices[0]; 21 22 for(let i = 0 ; i < prices.length ; ++i){ 23 if(prices[i] < min){ 24 min = prices[i]; 25 max = 0; 26 } 27 if(prices[i] > max){ 28 max = prices[i]; 29 } 30 if(max - min > return_val){ 31 return_val = max - min; 32 } 33 34 } 35 return return_val; 36 37 };