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.

jump game leetcode

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 :

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription