Best Time to Buy and Sell Stock |

Vipul Gupta
2 min readMay 12, 2021

I came across these two questions and found similarities.

  1. Buy and Sell only 1 time to get maximum profit.
  2. Buy and Sell multiple times to get maximum profit.

Here comes the solutions for the same, The code is the same for both the questions but with minor differences.

Solution 1: Buy and Sell single time:

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.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
class Solution {
public int maxProfit(int[] arr) {
int i =0;
int buy = Integer.MAX_VALUE;
int profit = 0;
while(i<arr.length){
if(arr[i]<buy){
buy = arr[i];
}
if(arr[i]>buy)
profit = Math.max(profit,arr[i]-buy);
i++;
}
if(buy!=Integer.MAX_VALUE)
return profit;
return 0;
}
}

Solution 2: Buy and Sell Multiple times:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
class Solution {
public int maxProfit(int[] prices) {
int buy = Integer.MAX_VALUE;
int profit = 0;

for(int i=0;i<prices.length;i++){
if(prices[i]<buy){
buy = prices[i];
}
else if(prices[i]>buy){
profit+=prices[i] - buy;
buy = prices[i];
}
}
return profit;
}
}

Happy Coding!

--

--