Best time to buy and sell stock

Asked atJGJMAN GroupMakeMyTripMicrosoft
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an array arr of n integers, where arr[i] represents price of the stock on the ith day. Determine the** maximum profit** achievable by buying and selling the stock at most once.

The stock should be purchased before selling it, and both actions cannot occur on the same day.

Input: arr = [10, 7, 5, 8, 11, 9] Output: 6 Explanation: Buy on day 3 (price = 5) and sell on day 5 (price = 11), profit = 11 - 5 = 6.

Input: arr = [5, 4, 3, 2, 1] Output: 0 Explanation: In this case, no transactions are made. Therefore, the maximum profit remains 0.

**Input: **arr = [3, 8, 1, 4, 6, 2]

  • 1 <= n<= 105
  • 0 <= arr[i] <= 106

cpp

class Solution{
public:
    int stockBuySell(vector<int> arr, int n){
        
    }
};

java

class Solution {
    public int stockBuySell(int[] arr, int n) {
       
    }
}

python

class Solution:
    def stockBuySell(self, arr, n):

javascript

class Solution {
    stockBuySell(arr, n) {
     
    }
}

csharp

class Solution
{
    public int stockBuySell(int[] arr, int n)
    {
       
    }
}

go

func stockBuySell(arr []int, n int) int {
	
}
Stuck? Show a way to structure it+
  1. 01Track the minimum stock price seen before the current day.
  2. 02Treat the current day as a possible sale and update the best profit.
  3. 03Then update the running minimum for future days.
  4. 04Keep zero profit when no profitable transaction exists.

Reference answer

Then expect these follow-ups

  • How would you return the buy and sell days?

    Tests: state tracking

  • What changes when unlimited transactions are allowed?

    Tests: variant recognition

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question