ποΈ Problems
121. Best Time to Buy and Sell Stock - Leetcode
You are given an array prices where prices[i] is the price of a given stock
on the ith day.
You want to maximize 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.
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
π€ First attempt
- Buy in
i
day, and then sell inj
day.
var maxProfit = function (prices) {
const N = prices.length;
let max = -Infinity;
for (let i = 0; i < N; i += 1) {
const buy = prices[i];
for (let j = i + 1; j < N; j += 1) {
const sell = prices[j];
if (buy > sell) continue;
if (max < sell - buy) max = sell - buy;
}
}
return max === -Infinity ? 0 : max;
};
π ββοΈ Failed time complexity : O(n^2)
- Input size is
10^5
, so that the nested loop will cause TLE.
β¨ Idea
- When does the maximum profit occur ?
- Buy the lowest price.
- Sell the highest price.
- Can you do this in
O(n)
?
π Update min price
let minPrice = Infinity;
for (const price of prices) {
if (minPrice > price) {
minPrice = price
} else {
...
}
}
π Update max profit
- I can't sell in the same day which I bought.
- If it's NOT a min price, update the profit.
let maxProfit = -Infinity
for (const price of prices) {
if (minPrice > price) {
...
} else {
const profit = price - minPrice
if (maxProfit < profit) maxProfit = profit
}
}
π₯ My Solution
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
let minPrice = Infinity;
let maxProfit = -Infinity;
for (const price of prices) {
if (minPrice > price) {
minPrice = price;
} else {
const profit = price - minPrice;
if (maxProfit < profit) maxProfit = profit;
}
}
return maxProfit === -Infinity ? 0 : maxProfit;
};