Given ticker value for a stock, for next n days, given what is the max profit that you can make ?
Eg - the max profit you can make is buy at time t1 @ 5 and sell @ t2 when stock was 12, to get max Profit of 7 dollars.
time - Stock Price
t0 - 10
t1 - 5
t2 - 12
t3 - 7
t4 - 12
Also - you can only trade once i.e you can buy and sell only 1 time.
so here is the solution of that problem .that problem is nothing just think like that if we have only one day stock values so we can buy or sell on that day only , so for general we can find the for up to kth day and we can find out for the k+1'th day ..
so algo is that maintain the 3 things first two pointer of buy and sell and one pointer of minimum values .we can make it in O(n) only
Just make a new array which contains the "lookahead" view, where we can see, which potential highest value we can gaini in future.
Another array just contains the lowest value so far. When the difference between the two arrays is max, there is the buying point. Selling point is, when the falling edge of the max array is reached.
public void highestGain(int[] prices) {
int[] maxPrices = new int[prices.length];
int[] minPrices = new int[prices.length];
maxPrices[maxPrices.length-1] = prices[prices.length-1];
minPrices[0] = prices[0];
for(int i = 1; i<prices.length; i++) {
int right = prices.length-i-1;
minPrices[i] = Math.min(minPrices[i-1], prices[i]);
maxPrices[right] = Math.max(maxPrices[right+1], prices[right]);
}
System.out.println("MaxPrices: " + Arrays.toString(maxPrices));
System.out.println("MinPrices: " + Arrays.toString(minPrices));
// find when to buy (when the difference of min/max is highest)
int maxDifference = maxPrices[0] - minPrices[0];
int maxDifferencePos = 0;
for(int i=0; i<minPrices.length; i++) {
int difference = maxPrices[i] - minPrices[i];
if(maxDifference < difference) {
maxDifference = difference;
maxDifferencePos = i;
}
}
// Now find the falling edge of max prices - there was the last peak
int sellPos = maxDifferencePos+1;
int lastPrice = maxPrices[maxDifferencePos];
for(; sellPos < maxPrices.length; sellPos++) {
if(lastPrice > maxPrices[sellPos]) {
sellPos --;
break;
}
}
System.out.println("Ideal to buy/sell: " + maxDifferencePos + ":" + sellPos);
}
No comments:
Post a Comment