Advertisement
1988coder

714. Best Time to Buy and Sell Stock with Transaction Fee

Dec 30th, 2018
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. /**
  2.  * Refer: 1)
  3.  * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108871/2-solutions-2-states-DP-solutions-clear-explanation!
  4.  * 2)
  5.  * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108870/Most-consistent-ways-of-dealing-with-the-series-of-stock-problems
  6.  *
  7.  * At day i, we may buy stock (from previous sell status) or do nothing (from
  8.  * previous buy status): buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i]);
  9.  *
  10.  * OR
  11.  *
  12.  * At day i, we may sell stock (from previous buy status) or keep holding (from
  13.  * previous sell status): sell[i] = Math.max(sell[i - 1], buy[i - 1] +
  14.  * prices[i]);
  15.  *
  16.  * Time Complexity: O(N)
  17.  *
  18.  * Space Complexity: O(1)
  19.  *
  20.  * N = length of input prices array.
  21.  */
  22. class Solution {
  23.     public int maxProfit(int[] prices, int fee) {
  24.         if (prices == null || prices.length <= 1) {
  25.             return 0;
  26.         }
  27.  
  28.         int buy = -prices[0];
  29.         int sell = 0;
  30.  
  31.         for (int price : prices) {
  32.             int prevSell = sell;
  33.             sell = Math.max(sell, buy + price - fee);
  34.             buy = Math.max(buy, prevSell - price);
  35.         }
  36.  
  37.         return sell;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement