121. Best Time to Buy and Sell Stock Leetcode Solution
Best Time to Buy and Sell Stock Leetcode Problem :
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.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Best Time to Buy and Sell Stock Leetcode Solution :
Constraints :
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
Example 1:
- Input: prices = [7,6,4,3,1]
- Output: 0
Approach :
1)We make 2 extra arrays, left and right
2)We initialize the first element of left array as the first element of prices
3)We initialize the last element of right array as the last element of prices
4)To get the maximum Profit, we need minimum from left array and maximum from right array.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: int maxProfit(vector< int>& prices) { int n=prices.size(); int l[n],r[n]; l[0]=prices[0]; r[n-1]=prices[n-1]; for(int i=1;i< n;i++){ l[i]=min(l[i-1],prices[i]); } for(int i=n-2;i>=0;i--){ r[i]=max(r[i+1],prices[i]); } int maxProfit=0; for(int i=0;i< n;i++){ maxProfit=max(maxProfit,r[i]-l[i]); } return maxProfit; } };
class Solution { public int maxProfit(int[] prices) { int min_price = prices[0]; int maxprof = 0; for(int i=1;i< prices.length;i++){ maxprof = Math.max(maxprof,prices[i]-min_price); min_price = Math.min(prices[i],min_price); } return maxprof; } }
class Solution: def maxProfit(self, prices: List[int]) -> int: min_price = prices[0] max_profit = 0 for price in prices[1:]: max_profit = max(max_profit, price - min_price) min_price = min(min_price, price) return max_profit
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment