Skip to content

Instantly share code, notes, and snippets.

@thmain
Created August 20, 2017 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/4512a19ad54e9f2af49ce390a2020fd3 to your computer and use it in GitHub Desktop.
Save thmain/4512a19ad54e9f2af49ce390a2020fd3 to your computer and use it in GitHub Desktop.
public class StockSingleSellBruteForce {
public static void maxProfit(int [] prices){
int profit = -1;
int buyDateIndex = prices[0];
int sellDateIndex = prices[0];
for (int i = 0; i <prices.length ; i++) {
for (int j = i; j <prices.length ; j++) {
if(prices[j]>prices[i] && (prices[j]-prices[i]>profit)) {
profit = prices[j] - prices[i];
buyDateIndex = i;
sellDateIndex = j;
}
}
}
System.out.println("Maximum Profit: " + profit + ", buy date index: " + buyDateIndex +
", sell date index: " + sellDateIndex);
}
public static void main(String[] args) {
int [] prices = { 200, 500, 1000, 700, 30, 400, 900, 400, 50};
maxProfit(prices);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment