Created
August 20, 2017 17:11
-
-
Save thmain/2ee51b24b4003f5086bbb10979e6f4f3 to your computer and use it in GitHub Desktop.
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 StockSingleSellDP { | |
public static void maxProfit(int[] prices) { | |
int period = prices.length; | |
int buyDateIndex = 0; | |
int tempIndex = 0; | |
int sellDateIndex = 0; | |
int current_profit = 0; | |
int max_sell_price = prices[period - 1]; //assign the last element | |
for (int i = period - 2; i > 0; i--) { | |
if (max_sell_price < prices[i]) { | |
max_sell_price = prices[i]; | |
tempIndex = i; | |
} else if (max_sell_price > prices[i]) { | |
if (current_profit < max_sell_price - prices[i]) { | |
current_profit = max_sell_price - prices[i]; | |
buyDateIndex = i; | |
sellDateIndex = tempIndex; | |
} | |
} | |
} | |
System.out.println("Maximum Profit(DP): " + current_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