Tutorialspoint
Problem
Solution
Submissions

Best Time to Buy and Sell Stock

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a Java program to find the maximum profit by buying and selling a stock. 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:
    • Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
    • No other transaction would result in a higher profit.
    • Therefore, the maximum profit is 5.
Example 2
  • Input: prices = [7,6,4,3,1]
  • Output: 0
  • Explanation:
    • The price keeps decreasing every day, so no transaction would result in a profit.
    • The best we can do is not to conduct any transaction, which gives a profit of 0.
    • Therefore, the maximum profit is 0.
Constraints
  • 1 ≤ prices.length ≤ 10^5
  • 0 ≤ prices[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
NumberEYSamsung
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 find the maximum profit
  • Keep track of the minimum price seen so far
  • For each price, calculate the potential profit if you sell at that price
  • Update the maximum profit if a larger profit is found
  • Return the maximum profit at the end

Steps to solve by this approach:

 Step 1: Check if the input array is valid (not null and has at least 2 elements). If not, return 0.

 Step 2: Initialize minPrice with the first price and maxProfit as 0.
 Step 3: Iterate through the prices starting from the second day.
 Step 4: If the current price is less than minPrice, update minPrice.
 Step 5: If selling at the current price yields a higher profit, update maxProfit.
 Step 6: Return the maximum profit after processing all prices.
 Step 7: Output: 5 for example 1 and 0 for example 2.

Submitted Code :