Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. public class StockSingleSellDP {
  2. public static void maxProfit(int[] prices) {
  3. int period = prices.length;
  4. int buyDateIndex = 0;
  5. int tempIndex = 0;
  6. int sellDateIndex = 0;
  7. int current_profit = 0;
  8. int max_sell_price = prices[period - 1]; //assign the last element
  9. for (int i = period - 2; i > 0; i--) {
  10. if (max_sell_price < prices[i]) {
  11. max_sell_price = prices[i];
  12. tempIndex = i;
  13. } else if (max_sell_price > prices[i]) {
  14. if (current_profit < max_sell_price - prices[i]) {
  15. current_profit = max_sell_price - prices[i];
  16. buyDateIndex = i;
  17. sellDateIndex = tempIndex;
  18. }
  19. }
  20. }
  21. System.out.println("Maximum Profit(DP): " + current_profit + ", buy date index: " + buyDateIndex +
  22. ", sell date index: " + sellDateIndex);
  23. }
  24.  
  25. public static void main(String[] args) {
  26. int[] prices = {200, 500, 1000, 700, 30, 400, 900, 400, 50};
  27. maxProfit(prices);
  28. }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement