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

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. 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.)

Return the maximum profit you can make.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
  • Buying at prices[0] = 1
  • Selling at prices[3] = 8
  • Buying at prices[4] = 4
  • Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. 

Note:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

买卖股票的最佳时机含手续费。这是股票系列的最后一题了。这道题允许你交易多次,但是每次交易的时候是有一个手续费,用fee表示。依然是请你返回获得利润的最大值。

思路依然是动态规划。还是创建一个二维的DP数组,dp[i][j]表示第 i 天持有和不持有股票的最大收益。j 只有可能是0或1,表示不持有股票和持有股票。这道题多的一个变量fee可以放在买入的时候,可以把他理解为成本的一部分。其他部分跟版本二的动态规划解法没有区别。分享一个写的很好的题解

时间O(n)

空间O(mn)

Java实现

 1 class Solution {
 2     public int maxProfit(int[] prices, int fee) {
 3         int len = prices.length;
 4         // corner case
 5         if (len < 2) {
 6             return 0;
 7         }
 8 
 9         // dp[i][j] 表示 [0, i] 区间内,到第 i 天(从 0 开始)状态为 j 时的最大收益'
10         // j = 0 表示不持股,j = 1 表示持股
11         // 并且规定在买入股票的时候,扣除手续费
12         int[][] dp = new int[len][2];
13         dp[0][0] = 0;
14         dp[0][1] = -prices[0] - fee;
15         for (int i = 1; i < len; i++) {
16             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
17             dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee);
18         }
19         return dp[len - 1][0];
20     }
21 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13704638.html