Created
October 17, 2013 07:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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