商品折扣后的最终价格单调栈

给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。 商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > iprices[j] <= prices[i]最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。 请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。

ini 复制代码
输入: prices = [8,4,6,2,3]
输出: [4,2,4,2,3]
java 复制代码
class Solution {
    public int[] finalPrices(int[] prices) {
        int n=prices.length;
        int[] ans=new int[n];
        Deque<Integer> stack=new ArrayDeque<Integer>();
        for(int i=n-1;i>=0;i--){
            while(!stack.isEmpty() && stack.peek()>prices[i]){
                stack.pop();
            }
            ans[i]=stack.isEmpty()?prices[i]:prices[i]-stack.peek();
            stack.push(prices[i]);
        }
        return ans;
    }
}
相关推荐
我学上瘾了21 小时前
Spring Cloud的前世今生
后端·spring·spring cloud
波波00721 小时前
ASP.NET Core 健康检查实战:不只是一个 /health 接口
后端·asp.net
小码哥_常1 天前
Spring Boot 搭建邮件发送系统:开启你的邮件自动化之旅
后端
故事和你911 天前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__1 天前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__1 天前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
石榴树下的七彩鱼1 天前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印
我叫黑大帅1 天前
为什么TCP是三次握手?
后端·网络协议·面试
我叫黑大帅1 天前
如何排查 MySQL 慢查询
后端·sql·面试
techdashen1 天前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust