Source:http://programming4interviews.wordpress.com/category/dynamic-programming/
Given a week`s daily prices of a stock, find out the days in which we should buy and sell the stocks such that the profit is maximum.
This is a common interview question and also very special to me as this was asked to me in an interview I attended some time back. I could not crack it fully during the interview. Taken up multiple times to solve, but left it half way. Today I am happy that finally I could crack this problem and also write a working code for it. Interestingly the answer was always in front of me here . Its just that i did not pay much attention to it.
Go through the elements in the array, keep track of the maximum profit and minimum stock price seen till then, you have your answer.
public static int findMaxProfit(int[] stockPriceSamples) { int maxProfit = 0; int minTillNow = stockPriceSamples[0]; for (int i = 0; i < stockPriceSamples.length; i++) { int profit = stockPriceSamples[i] - minTillNow; maxProfit = Math.max(profit, maxProfit); minTillNow = Math.min(stockPriceSamples[i], minTillNow); } return maxProfit; }
The driver code
public static void main(String[] args) { int[] stockPrices = new int[] { 5, 2, 10, 3, 10, 5, 5, 1, 17, 4, 100 }; System.out.println(findMaxProfit(stockPrices)); }
The answer is
99
Again this is not something which is newly invented. I could find at least 3-4 links where this problem is explained very well. I personally like the code talk for me . For those who want to read more and to see some alternate solutions, I found this link to be very useful.