【微软算法面试高频题】买卖股票的最佳时机含手续费

260 阅读2分钟

微软和谷歌的几个大佬组织了一个面试刷题群,可以加管理员VX:sxxzs3998(备注掘金),进群参与讨论和直播

股票系列问题

建议六道题目按顺序一起看,层层递进,一次解决六道题目

【微软算法面试高频题】买卖股票的最佳时机

【微软算法面试高频题】买卖股票的最佳时机 II

【微软算法面试高频题】最佳买卖股票时机含冷冻期

【微软算法面试高频题】买卖股票的最佳时机含手续费

【微软算法面试高频题】买卖股票的最佳时机 III

【微软算法面试高频题】买卖股票的最佳时机 IV

1. 问题

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例 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

示例 2:
输入:prices = [1,3,7,5,10,3], fee = 3
输出:6

2. 解析

与题目 买卖股票的最佳时机 II 一样

解析也一样 ,因此建议先看上一篇买卖股票的最佳时机 II

区别在于多了个fee,在卖出股票时减去就行了 即:profit[i][0] = Math.max(profit[i-1][0], profit[i-1][1] + prices[i] - fee);

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int profit[][] = new int[prices.length][2];
        profit[0][0] = 0;
        profit[0][1] = -prices[0];
        for(int i=1 ; i<prices.length; i++){
            profit[i][0] = Math.max(profit[i-1][0], profit[i-1][1] + prices[i] - fee);
            profit[i][1] = Math.max(profit[i-1][1], profit[i-1][0] - prices[i]);
        }
        return profit[prices.length-1][0];
    }
}

同理降低空间复杂度

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int profit_0 = 0, profit_1 = -prices[0], temp = 0;
        for(int i = 0; i<prices.length; i++){
            temp = profit_0;
            profit_0 = Math.max(profit_0, profit_1 + prices[i] - fee);
            profit_1 = Math.max(profit_1, temp - prices[i]);
            temp = profit_0;
        }
        return profit_0;
    }
}

微软和谷歌的几个大佬组织了一个面试刷题群,可以加管理员VX:sxxzs3998(备注掘金),进群参与讨论和直播