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

441 阅读2分钟

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

股票系列问题

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

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

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

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

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

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

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

1. 问题

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

示例:

输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

2. 解析

做法与上一题 买卖股票的最佳时机 II 完全一样

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

只不过为了处理冷冻期,购买只能根据profit[i-2][0]

class Solution {
    public int maxProfit(int[] prices) {
        int profit[][] = new int[prices.length][2];
        int preProfit = 0;
        profit[0][0] = 0;
        profit[0][1] = -prices[0];
        for(int i=1 ; i<prices.length; i++){
            if(i==1){   //避免profit[i-2][0]中i-2数组越界,把i=1从循环中提出来
                preProfit=0;
            }else{
                preProfit=profit[i-2][0];
            }
            profit[i][0] = Math.max(profit[i-1][0], profit[i-1][1]+prices[i]);
            profit[i][1] = Math.max(profit[i-1][1], preProfit-prices[i]);
        }
        return profit[prices.length-1][0];

    }
}

同理降低空间复杂度

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

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