The core strategy is find the maximum difference between given stock price and lowest price of previous stock prices. Iterate through the array following this strategy and keep on updating maximum difference variable if required. At the end of complete iteration the value of maximum difference variable will be maximum profit. Sample example as below:
public class MaxStockprofit {
public static void main(String[] args) {
double[] stockPrice = { 310, 315, 275, 295, 260, 270, 290, 230, 255,
250 };
double maxProfit = getMaxProfit(stockPrice);
System.out.println("Max Profit:" + maxProfit);
}
private static double getMaxProfit(final double[] stockPrice) {
double minPrice = Double.MAX_VALUE;
double maxProfit = 0;
for (double price : stockPrice) {
// maxProfit=Math.max(maxProfit,price-minPrice);
maxProfit = maxProfit > (price - minPrice) ? maxProfit
: (price - minPrice);
// minPrice=Math.min(price,minPrice);
minPrice = minPrice < price ? minPrice : price;
}
return maxProfit;
}
}
public class MaxStockprofit {
public static void main(String[] args) {
double[] stockPrice = { 310, 315, 275, 295, 260, 270, 290, 230, 255,
250 };
double maxProfit = getMaxProfit(stockPrice);
System.out.println("Max Profit:" + maxProfit);
}
private static double getMaxProfit(final double[] stockPrice) {
double minPrice = Double.MAX_VALUE;
double maxProfit = 0;
for (double price : stockPrice) {
// maxProfit=Math.max(maxProfit,price-minPrice);
maxProfit = maxProfit > (price - minPrice) ? maxProfit
: (price - minPrice);
// minPrice=Math.min(price,minPrice);
minPrice = minPrice < price ? minPrice : price;
}
return maxProfit;
}
}
No comments:
Post a Comment