/** * An iterative solution to the Stock Market Problem from Xeno Fish * * The idea behind this iterative solution is that we only need to consider subarrays of the original array * where the subarray begins at some minimum value and continues until the next minimum value. For example, * consider the array: * * [min.....new min...end] * * Any solution to the problem is entirely contained in either the subarray: * * [min...new min-1] * * or the subarray: * [new min...end] * * In other words, it is never better to have a buy date and sell date that spans across the subarrays * @author alchambers * */ public class Iterative implements StockIfc { @Override public StockInfo solve(int[] array) { StockInfo answer = new StockInfo(); answer.profit = Integer.MIN_VALUE; int currentBuy = 0; int currentSell = 0; for(int i = 1; i < array.length; i++){ // We've found a new minimum...we're starting a new subarray if(array[i] < array[currentBuy]){ currentBuy = i; } // Search within the subarray for a better profit else if(array[currentSell] - array[currentBuy] > answer.profit){ answer.profit = array[currentSell] - array[currentBuy]; answer.buy_index = currentBuy; answer.sell_index = currentSell; } } return answer; } }