Understand Best Time to Buy and Sell Stock Problem

Problem Name: Best Time to Buy and Sell Stock
Problem Description:

Maximum Profit from Stock Trading

Objective:
To determine the maximum profit that can be achieved from buying and selling stock on given days, where the price of the stock is provided as an array.


Steps:

1. Initialize Variables:

  • maxProfit: This variable will store the maximum profit encountered so far.
  • minSoFar: This variable represents the minimum stock price encountered up to the current day. Initialize it to the stock price on the first day.

2. Iterate Through the Array:

  • Use a for loop to iterate through the array of stock prices.
    • For each day, calculate the potential profit by subtracting minSoFar from the current stock price.
    • If this potential profit is greater than the current maxProfit, update maxProfit with the new potential profit.
    Additionally, update minSoFar to be the minimum of its current value and the current stock price. This ensures that you always have the lowest price encountered up to the current day.

3. Return the Result:

  • After iterating through the entire array, the final value of maxProfit will hold the maximum profit achievable by buying and selling the stock.

Test Cases:

Test Case 1:

Input:
prices = [7, 1, 5, 3, 6, 4]

Output:
Maximum Profit = 5
Explanation:

  • Buy on day 2 (price = 1), sell on day 5 (price = 6), profit = 6 - 1 = 5.

Test Case 2:

Input:
prices = [7, 6, 4, 3, 1]

Output:
Maximum Profit = 0
Explanation:

  • No transaction is made as prices are decreasing. No profit can be achieved.

Test Case 3:

Input:
prices = [1, 2, 3, 4, 5]

Output:
Maximum Profit = 4
Explanation:

  • Buy on day 1 (price = 1), sell on day 5 (price = 5), profit = 5 - 1 = 4.

Test Case 4:

Input:
prices = [3, 2, 6, 5, 0, 3]

Output:
Maximum Profit = 4
Explanation:

  • Buy on day 2 (price = 2), sell on day 3 (price = 6), profit = 6 - 2 = 4.

Code Example:

def maxProfit(prices):
    maxProfit = 0
    minSoFar = prices[0]
    
    for price in prices:
        maxProfit = max(maxProfit, price - minSoFar)
        minSoFar = min(minSoFar, price)
    
    return maxProfit
Category:
  • Array
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/pascals-triangle/description/

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

Main Function is not defined.

Helper Function:

public static int maxProfit(vector<int>& prices){

int maxprofit = 0;

int minsofar = prices[0];

for(int i = 0; i < prices.size();i++){

minsofar = min(minsofar,prices[i]);

int profit = prices[i] - minsofar;

maxprofit = max(maxprofit, profit);

}

return maxprofit;

}//function end

Utility Functions and Global variables:

Utility Function is not required.