Created
July 1, 2022 00:03
-
-
Save blentz100/d5147569eb19c0ec3a27158b489e22fa to your computer and use it in GitHub Desktop.
Best Time to Buy - Leetcode Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ | |
// in progress, almost there! | |
/** | |
* @param {number[]} prices | |
* @return {number} | |
*/ | |
var maxProfit = function(prices) { | |
let currentBest = 0; | |
//let pricesCopy = [...prices] | |
for(let i = 0; i < prices.length; i++){ | |
console.log('prices[i]', prices[i]) | |
console.log(Math.max(...prices)) | |
if(Math.max(...prices)-prices[i] > currentBest){ | |
currentBest = Math.max(...prices)-prices[i]; | |
console.log('currentBest:', currentBest) | |
} | |
prices.shift(); | |
} | |
return currentBest | |
}; | |
maxProfit([7,1,5,3,6,4]) |
This works and is very fast! Going through the array backwards made it so much easier.
Spoiler
const maxProfit = function(prices) {
let profit = 0
let highPrice = 0
for (let i = prices.length - 1; i >= 0; i--) {
if (prices[i] > highPrice) highPrice = prices[i]
if (highPrice - prices[i] > profit) profit = highPrice - prices[i]
}
return profit
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems to work, but it is still too slow and exceeds time limit.
Spoiler