Skip to content

Commit 8748a21

Browse files
refactor 714
1 parent 82d88b8 commit 8748a21

File tree

1 file changed

+8
-32
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+8
-32
lines changed

src/main/java/com/fishercoder/solutions/_714.java

+8-32
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,12 @@
11
package com.fishercoder.solutions;
22

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-
*/
293
public class _714 {
304
public static class Solution1 {
31-
/**O(n) time
5+
/**
6+
* O(n) time
327
* O(n) space
338
* credit: https://discuss.leetcode.com/topic/108009/java-c-clean-code-dp-greedy
34-
* */
9+
*/
3510
public int maxProfit(int[] prices, int fee) {
3611
int n = prices.length;
3712
if (n < 2) {
@@ -49,17 +24,18 @@ public int maxProfit(int[] prices, int fee) {
4924
}
5025

5126
public static class Solution2 {
52-
/**O(n) time
27+
/**
28+
* O(n) time
5329
* O(1) space
5430
* credit: https://leetcode.com/articles/best-time-to-buy-and-sell-stock-with-transaction-fee/
55-
*
31+
* <p>
5632
* cash: the max profit we could have if we did not have a share of stock in hand
5733
* hold: the max profit we could have if we hold one share of stack in hand
58-
*
34+
* <p>
5935
* to transition from the i-th day to the i+1 th day, we have two options:
6036
* 1. sell our stock: cash = Math.max(cash, hold + prices[i] - fee)
6137
* 2. buy a stock: hold = Math.max(hold, cash - prices[i])
62-
* */
38+
*/
6339
public int maxProfit(int[] prices, int fee) {
6440
int cash = 0;
6541
int hold = -prices[0];

0 commit comments

Comments
 (0)