Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Created October 17, 2013 07:22
Show Gist options
  • Save anoopelias/7020476 to your computer and use it in GitHub Desktop.
Save anoopelias/7020476 to your computer and use it in GitHub Desktop.
Given the price of stock for every minute past midnight, find the time at which you would have bought and sold for maximum profit.
public class AppleStock {
public static void main(String[] args) {
int[] stockPricesYesterday = { 500, 501, 503, 495, 503 };
int buy = -1;
int sell = -1;
int lowest = -1;
for (int i = 0; i < stockPricesYesterday.length; i++) {
if (buy == -1) {
buy = i;
lowest = i;
} else {
if (sell == -1) {
sell = i;
} else {
int currProfit = stockPricesYesterday[sell]
- stockPricesYesterday[buy];
int ifSellNowProfit = stockPricesYesterday[i]
- stockPricesYesterday[lowest];
if (ifSellNowProfit > currProfit) {
buy = lowest;
sell = i;
}
}
if (stockPricesYesterday[i] < stockPricesYesterday[lowest])
lowest = i;
}
}
System.out.println("buy : " + buy + ", sell : " + sell + ", profit : "
+ (stockPricesYesterday[sell] - stockPricesYesterday[buy]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment