[leetcode/lintcode 题解] 美团面试题:最终优惠价
2020-07-16 05:38
555 查看
【题目描述】
一位店主需要完成一项销售任务,他将要出售的物品排成一排。
从左侧开始,店主以其全价减去位于该物品右侧的第一个价格较低或价格相同的商品的价格。
如果右侧没有价格低于或等于当前商品价格的商品,则以全价出售当前商品。
你需要返回每一个物品实际售出价格。
在线评测地址:
https://www.lintcode.com/problem/final-discounted-price/?utm_source=sc-csdn-fks
示例 1:
输入: Prices = [2, 3, 1, 2, 4, 2] 输出: [1, 2, 1, 0, 2, 2] 解释:第0个和第1个物品右边第一个更低的价格都是1,所以实际售价需要在全价上减去1, 第3个物品右边第一个更低的价格是2,所以实际售价要在全价上面减去2。
示例 2:
输入: Prices = [1, 2, 3, 4, 5] 输出: [1, 2, 3, 4, 5] 解释: 每一个物品都保持原价,他们的右边都没有等于或者更低价格的物品
【题解】
public class Solution { /** * @param prices: a list of integer * @return: return the actual prices */ public int[] FinalDiscountedPrice(int[] prices) { // write your code here int[] res = new int[prices.length]; Stack<Integer> s = new Stack<>(); for(int i = 0;i < prices.length;i++) res[i] = prices[i]; for(int i = 0;i < prices.length;i++){ while(!s.isEmpty() && prices[s.peek()] >= prices[i]) { int index = s.pop(); res[index] = prices[index] - prices[i]; } s.push(i); } return res; } }
更多语言代码参见:https://www.lintcode.com/problem/final-discounted-price/?utm_source=sc-csdn-fks
相关文章推荐
- [leetcode/lintcode 题解] Google面试题:奇偶跳
- [leetcode/lintcode 题解] Amazon面试题:分享巧克力
- [leetcode/lintcode 题解] 微软面试题:拿走瓶子
- [leetcode/lintcode 题解] 尽量减少恶意软件的传播II
- [leetcode/lintcode 题解] 蛇梯棋
- [leetcode/lintcode 题解] 湖面逃跑
- LeetCode 269 / LintCode 892 Alien Dictionary
- lintcode/leetcode由易至难第20题:Integer Break
- lintcode/leetcode由易至难第7题:Distribute Candies
- lintcode/leetcode由易至难第13题:Max Consecutive Ones
- LeetCode 285 / LintCode 448 Inorder Successor in BST
- lintcode/leetcode由易至难第16题:Reshape the Matrix
- lintcode&九章算法——Google 面试题 | 数组的度数 ? 待解决
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value
- 剑指offer 面试题39:判断平衡二叉树(LeetCode 110. Balanced Binary Tree) 题解
- 排颜色问题——数组 leetcode lintcode
- lintcode/leetcode由易至难第19题:Teemo Attacking
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- lintcode/leetcode由易至难第22题:Complex Number Multiplication
- Lintcode182 Delete Digits solution 题解