1
1
package com .fishercoder .solutions ;
2
2
3
- /**
4
- * 714. Best Time to Buy and Sell Stock with Transaction Fee
5
- *
6
- * Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i;
7
- * and a non-negative integer fee representing a transaction fee.
8
- * You may complete as many transactions as you like,
9
- * but you need to pay the transaction fee for each transaction.
10
- * You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
11
-
12
- Return the maximum profit you can make.
13
-
14
- Example 1:
15
- Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
16
- Output: 8
17
- Explanation: The maximum profit can be achieved by:
18
- Buying at prices[0] = 1
19
- Selling at prices[3] = 8
20
- Buying at prices[4] = 4
21
- Selling at prices[5] = 9
22
- The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
23
-
24
- Note:
25
- 0 < prices.length <= 50000.
26
- 0 < prices[i] < 50000.
27
- 0 <= fee < 50000.
28
- */
29
3
public class _714 {
30
4
public static class Solution1 {
31
- /**O(n) time
5
+ /**
6
+ * O(n) time
32
7
* O(n) space
33
8
* credit: https://discuss.leetcode.com/topic/108009/java-c-clean-code-dp-greedy
34
- * * /
9
+ */
35
10
public int maxProfit (int [] prices , int fee ) {
36
11
int n = prices .length ;
37
12
if (n < 2 ) {
@@ -49,17 +24,18 @@ public int maxProfit(int[] prices, int fee) {
49
24
}
50
25
51
26
public static class Solution2 {
52
- /**O(n) time
27
+ /**
28
+ * O(n) time
53
29
* O(1) space
54
30
* credit: https://leetcode.com/articles/best-time-to-buy-and-sell-stock-with-transaction-fee/
55
- *
31
+ * <p>
56
32
* cash: the max profit we could have if we did not have a share of stock in hand
57
33
* hold: the max profit we could have if we hold one share of stack in hand
58
- *
34
+ * <p>
59
35
* to transition from the i-th day to the i+1 th day, we have two options:
60
36
* 1. sell our stock: cash = Math.max(cash, hold + prices[i] - fee)
61
37
* 2. buy a stock: hold = Math.max(hold, cash - prices[i])
62
- * * /
38
+ */
63
39
public int maxProfit (int [] prices , int fee ) {
64
40
int cash = 0 ;
65
41
int hold = -prices [0 ];
0 commit comments