logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

122. Best Time to Buy and Sell Stock II

2 min read
On this pageIntuition
IntuitionApproachComplexityCode

Given an integer array prices , prices[i] is the price of a given stock on the ith day. If can hold only a single share and can buy and/or sell the stock on same day.

Find the maximum profit possible.


# Intuition

  • To achieve the max profit we need to buy on low day and sell on high day.
  • Since we can buy/sell multiple times we perform trades where price\[i]<price\[i+1]price\[i] < price\[i+1]price\[i]<price\[i+1]
  • If price\[i−1]<price\[i]<price\[i+1]price\[i-1] < price\[i] < price\[i+1]price\[i−1]<price\[i]<price\[i+1] we hold on day iii as we can sell on day i+1i+1i+1.

# Approach

  • Iterate over the array while maintaining buy price.
  • If we encounter day where price next day will be higher we hold
  • If the price the next day is less, sell now and buy tomorrow

# Complexity

  • Time complexity : O(1)\text{O}(1)O(1)
    • we iterate over the array only once
  • Space complexity : O(1)\text{O}(1)O(1)
    • no extra space is needed

# Code

public int maxProfit(int[] prices) {
	int maxProfit= 0, buyPrice = -1;
 
 
	for (int i = 0; i < prices.length -1; i++ ) {
		if(prices[i] <= prices[i+1]) {
			// hold if bought earlier
			// if we haven't baought earlier buy now
			if(buyPrice == -1) buyPrice = prices[i];
		} else {
			if(buyPrice != -1) {
				maxProfit += prices[i] - buyPrice;
				
				// to check if we can buy on same day for profit
				buyPrice = -1;
				i--;	
			}	
		}
	}
	
	// we bought at some point but couldn't sell
	// as everyday price increased so sell on the last day
 
	if(buyPrice != -1) {
		maxProfit += prices[prices.length-1] - buyPrice;
	}
	
	return maxProfit;
}
←Previous121. Best Time to Buy and Sell StockNext→189. Rotate Array

On this page

IntuitionApproachComplexityCode