Published
- 2 min read
Best time to buy and sell stock
Best time to buy and sell stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Example : int arr[] = new int[]4
There are variations to this problem
- How would you modify this to return the buying and selling days instead of just the profit?
- How would you solve if you’re allowed to do multiple transactions (buy and sell multiple times)?
private int bestTimeToBuyAndSellStock(int [] array) {
/*
I want to buy at a day lowest in price and sell at the day highest in price
keep moving fwd to find the minimum and max at each index,
once you reach the end see what the max and min and sub to get output,
if you cant get minimum you will get maximum
*/
if(array.length == 1 || array == null) {
return 0;
}
int minPrice= array[0];
int maxProfit = 0;
for (int i=1; i< array.length;i++){
if(array[i] < minPrice) {
minPrice = array[i];
} else {
maxProfit = Math.max(maxProfit, array[i]-minPrice);
}
}
return maxProfit;
}