终端某合作经销商遇到一个烦恼,由于下半年各平台的打折活动频繁,其终端商品价格具有一定波动性。经销商为了保证获取最大利益,将该商品在连续的K天内的价格记录在了数组prices中.经销商在某天(设为i) 决定购买某商品,将它们存入仓库。并在另外一天(设为j) ,经销商将 商品卖出(i< = j) , 同时他还需要付给该仓库j - i元的租金(每天租金为1) .此经销商请你帮忙判断一下基于现在的规则, 最多可以嫌多少利润,并输出• 注:为了简化实现,整个过程只买卖一次. 示例1: 输入:prices = [2,1,5] 输出:3 解释:最优策略是第二天买入,第三天卖出,租金为1,利润为5-1 -1 =3 J 示例2: 输入:prices = [7,6,5] 输出:0 解释:最优策略是任意一天买入,当天卖出,利润为0 函数名称自定义,输入是一个数组;输出整形
function maxProfit(prices) {
let buy = -prices[0];
let sell = 0;
let left = 0, right = 0, temp = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] === temp) continue;
// 找到出售时间,设置为right
if (buy + prices[i] > sell) {
right = i;
sell = Math.floor(buy + prices[i] - (right - left));//售价-进价-租金
temp = prices[i];
}
// 找到购买时间,设置为left
if (sell - prices[i] >= buy) {
left = i;
buy = sell - prices[i];
}
}
return sell;
}