Tutorialspoint
Problem
Solution
Submissions

Best Time to Buy and Sell Stock

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

Write a JavaScript program to find the maximum profit you can achieve from buying and selling a stock. You are given an array of prices where prices[i] is the price of a given stock on the ith day. You can choose a single day to buy one stock and choose 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:
    • Consider all possible buy-sell combinations.
    • Buy on day 2 (price = 1) and sell on day 5 (price = 6).
    • Profit = 6 - 1 = 5. This is the maximum profit possible.
    • Other combinations like buy at 1, sell at 5 gives profit of 4, which is less than 5.
Example 2
  • Input: prices = [7, 6, 4, 3, 1]
  • Output: 0
  • Explanation:
    • The prices are in descending order.
    • There is no day where selling gives a profit.
    • Any buy day followed by a sell day results in a loss.
    • Since we cannot achieve any profit, return 0.
Constraints
  • 1 ≤ prices.length ≤ 10^5
  • 0 ≤ prices[i] ≤ 10^4
  • You must buy before you sell
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysPwCZomato
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

  • Keep track of the minimum price seen so far as you iterate through the array
  • For each price, calculate the profit if you sell on that day
  • The profit is the current price minus the minimum price seen so far
  • Keep track of the maximum profit encountered
  • Update the minimum price and maximum profit as you progress through the array

Steps to solve by this approach:

 Step 1: Handle edge case where array has 1 or fewer elements (no profit possible).
 Step 2: Initialize minPrice with the first day's price and maxProfit as 0.
 Step 3: Iterate through the prices array starting from the second day.
 Step 4: For each day, calculate the potential profit by selling on that day (current price - minimum price so far).
 Step 5: Update the maximum profit if the current profit is greater.
 Step 6: Update the minimum price if the current price is lower than the previous minimum.
 Step 7: Return the maximum profit after checking all possible selling days.

Submitted Code :