Citadel screening round | Senior Software Engineer

Best time to buy and sell stock. Given the array of prices, return the buy and sell combination to get maximum profit.

e.g.
int price[] = { 100, 102, 104, 80, 140, 211, 200 };
Buy on day: 0 Sell on day: 2
Buy on day: 3 Sell on day: 5

so an extension on Best time to buy and sell stock II : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

Solution ( something on the lines of this)

List<int[]> result = new ArrayList<>();
for(int i=1; i< prices.length; i++){
	if(prices[i]> prices[i-1]){
		buy = i-1;
		while(i < prices.length && prices[i]> prices[i-1])	i++;
		sell = i-1;
		result.add(new int[] {buy, sell});
		i--;
	}
}
return result;

Follow up : If given a initial amount of $1000, what would be the final amount after doing these transactions => initial amount plus profit

Initial amount provides the ability to buy more number of shares for a given stock
so just adding that part in the above code:

for(int i=1; i< prices.length; i++){
	if(prices[i]> prices[i-1]){
		buy = i-1;
		shares = initialAmount/prices[buy];
		while(i < prices.length && prices[i]> prices[i-1])	i++;
		sell = i-1;
		profit = (prices[sell] - prices[buy]) * shares;
		totalProfit += profit;
		//result.add(new int[] {buy, sell});
		i--;
	}
}
return totalProfit;
//return result;
Comments (1)