在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Your are given an array of integers 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:
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. Note:
给定一个整数数组 你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。 返回获得利润的最大值。 示例 1: 输入: prices = [1, 3, 2, 8, 4, 9], fee = 2 输出: 8 解释: 能够达到的最大利润: 在此处买入 prices[0] = 1 在此处卖出 prices[3] = 8 在此处买入 prices[4] = 4 在此处卖出 prices[5] = 9 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8. 注意:
Runtime: 796 ms
Memory Usage: 19.8 MB
1 class Solution { 2 func maxProfit(_ prices: [Int], _ fee: Int) -> Int { 3 var sold:Int = 0 4 var hold:Int = -prices[0] 5 for price in prices 6 { 7 var t:Int = sold 8 sold = max(sold, hold + price - fee) 9 hold = max(hold, t - price) 10 } 11 return sold 12 } 13 } 880ms 1 class Solution { 2 func maxProfit(_ prices: [Int], _ fee: Int) -> Int { 3 var cash = 0, hold = -prices[0] 4 for i in prices.indices { 5 cash = max(cash, hold + prices[i] - fee) 6 hold = max(hold, cash - prices[i]) 7 } 8 return cash 9 } 10 11 func dpMaxProfit(_ prices: [Int], _ fee: Int, _ index: Int, _ end: Int, _ profit: Int, _ buyed: Bool) -> Int { 12 13 if index >= end { 14 return profit 15 } 16 17 if buyed { 18 let sum2 = dpMaxProfit(prices, fee, index+1, end, profit, false) 19 let sum3 = dpMaxProfit(prices, fee, index+1, end, profit - fee + prices[index], false) 20 return max(sum2, sum3) 21 } 22 else { 23 let sum1 = dpMaxProfit(prices, fee, index+1, end, profit - prices[index], true) 24 let sum2 = dpMaxProfit(prices, fee, index+1, end, profit, false) 25 return max(sum1, sum2) 26 } 27 } 28 } 948ms 1 class Solution { 2 func maxProfit(_ prices: [Int], _ fee: Int) -> Int { 3 var totalProfit = 0, currProfit = 0, buy = 0, sell = 0 4 for i in 0..<prices.count { 5 if prices[i] < prices[buy] || prices[sell] - prices[i] > fee { 6 buy = i 7 sell = i 8 totalProfit += currProfit 9 currProfit = 0 10 } else if prices[i] > prices[sell] && prices[i] - prices[buy] > fee { 11 sell = i 12 currProfit = prices[sell] - prices[buy] - fee 13 } 14 } 15 totalProfit += currProfit 16 return totalProfit 17 } 18 }
|
请发表评论