Tutorialspoint
Problem
Solution
Submissions

Best Time to Buy and Sell Stock

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

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.

Example 1
  • Input: prices = [7,1,5,3,6,4]
  • Output: 5
  • Explanation:
     Step 1: Buy on day 1 (price = 1)
     Step 2: Sell on day 4 (price = 6)
     Step 3: Profit = 6 - 1 = 5
     Step 4: There is no other combination that gives a higher profit
Example 2
  • Input: prices = [7,6,4,3,1]
  • Output: 0
  • Explanation:
     Step 1: Prices are in decreasing order
     Step 2: No profit is possible as buying and then selling later always results in a loss
     Step 3: Return 0 as we choose not to do any transaction
Constraints
  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
  • You can only buy once and sell once
  • Time Complexity: O(n) where n is the length of the prices array
  • Space Complexity: O(1)
ArraysNumberTech MahindraGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a single pass approach to track the minimum price seen so far
  • For each price, calculate the potential profit by subtracting the minimum price from the current price
  • Update the maximum profit if the current potential profit is greater
  • Continue this process for all prices
  • Return the maximum profit found (or 0 if no profit is possible)

Steps to solve by this approach:

 Step 1: Check if the array has less than 2 elements. If so, return 0 as no profit is possible.

 Step 2: Initialize minPrice to the first price and maxProfit to 0.
 Step 3: Iterate through the prices array starting from the second price.
 Step 4: For each price, check if it's lower than the minPrice. If so, update minPrice.
 Step 5: If the current price is not a new minimum, calculate the potential profit by selling at the current price.
 Step 6: Update maxProfit if the current potential profit is greater than the existing maxProfit.
 Step 7: After examining all prices, return the maxProfit.

Submitted Code :