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

给你一个数组 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;
    }
}
相关推荐
骄马之死7 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
Frostnova丶7 小时前
【算法笔记】数学知识
笔记·算法
吴可可1237 小时前
AutoCAD 2016与2014二次开发关键差异
算法
GoGeekBaird8 小时前
Anthropic技能"(Skills)的经验分享
后端
王码码20358 小时前
多台服务器怎么统一看状态?Beszel 轻量监控,搭起来不费事
运维·服务器·后端·安全·阿里云·接口·web
郑洁文8 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
雨白9 小时前
哈希:以时间换空间的算法实战
算法
螺丝钉code9 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
指令集梦境10 小时前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
摇滚侠10 小时前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea