Solve LeetCode problem #121 Best Time to Buy and Sell Stock
In this article, we will be discussing the solution to the LeetCode problem #121 - Best Time to Buy and Sell Stock.
Problem Overview
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.
For instance:
1- Example 1:2 - Input: `prices = [7,1,5,3,6,4]`3 - Output: `5`4 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.5 Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.6- Example 2:7 - Input: `prices = [7,6,4,3,1]`8 - Output: `0`9 - Explanation: In this case, no transactions are done, and the max profit = 0.
Solution
You can also check the video solution.
The idea of stocks are that you buy them on low price and sell that on high price. Basically we just need to find the lowest price and the highest price after that day.
The algorithm is as follows:
- Initialize the max profit and the lowest price to 0
- Loop over the array
- Check if the index is 0
- If yes then set the lowest price to the current price and return
- If not then
- Calculate the profit by subtracting the current price from the lowest prices
- Set the lowest price to the minimum of the current price and the lowest prices
- Set the max profit to the maximum of the profit and the max profit
- Check if the index is 0
- Return the max profit
1/**2 * @param {number[]} prices3 * @return {number}4 */5var maxProfit = function (prices) {6 let maxProfit = 07 let lowestPrice = 089 prices.forEach((price, index) => {10 if (!index) {11 lowestPrice = price12 return13 }1415 const profit = price - lowestPrice16 lowestPrice = Math.min(lowestPrice, price)17 maxProfit = Math.max(profit, maxProfit)18 })1920 return maxProfit21}
Shameless Plug
I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
Contacts
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: