121. Best Time to Buy and Sell Stock - Easy
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximise your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
Example:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Constraints:
1 <= prices.length <= 10**5
0 <= prices[i] <= 10**4
Solution:
var maxProfit = function(prices) {
let buyPrice = prices[0];
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (buyPrice > prices[i]) {
buyPrice = prices[i];
}
profit = Math.max(profit, prices[i] - buyPrice);
}
return profit;
}
Thoughts:
This one really stumped me. I tried to get it working by sorting the prices array and comparing the indexOf the smallest and largest values, which passes for most test cases, but it is not the correct solution for this and would have been really slow. I definitely struggle with algebra-type questions where we have 2 of the 3 inputs and need to work out the final one, so you have to switch it around similar to the twoSum problem. I would give my confidence in this as a 3/10 and need to tackle more algebra type questions.
Comments
Post a Comment