I have problem with solving leetcode exercise.
the exercise: 121. Best Time to Buy and Sell Stock
I wrote my code like below. it’s working with some examples in my computer, but there is problem with time limit on leetcode. could you help me with your solution and explanation. thank you.
function maxProfit(prices) {
let maxProfit = 0, len = prices.length;
for (let buy = 0; buy < len; buy++) {
for (let sell = buy + 1; sell < len; sell++) {
let profit = prices[sell] - prices[buy];
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
}
let prices1 = [7, 1, 5, 3, 6, 4]; // => 5
let prices2 = [7, 6, 4, 3, 1]; // => 0
console.log("01:=> " + maxProfit(prices1));
console.log("02:=> " + maxProfit(prices2));
it’s working with 2 examples. but there is an error with time limit on leetcode