Skip to content

1475. Final Prices With a Special Discount in a Shop 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> finalPrices(vector<int>& prices) {
    vector<int> ans{prices};
    stack<int> stack;

    for (int j = 0; j < prices.size(); ++j) {
      // stack[-1] : = i in the problem description.
      while (!stack.empty() && prices[j] <= prices[stack.top()])
        ans[stack.top()] -= prices[j], stack.pop();
      stack.push(j);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int[] finalPrices(int[] prices) {
    int[] ans = prices.clone();
    Deque<Integer> stack = new ArrayDeque<>();

    for (int j = 0; j < prices.length; ++j) {
      // stack[-1] := i in the problem description.
      while (!stack.isEmpty() && prices[j] <= prices[stack.peek()])
        ans[stack.pop()] -= prices[j];
      stack.push(j);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def finalPrices(self, prices: List[int]) -> List[int]:
    ans = prices.copy()
    stack = []

    for i, price in enumerate(prices):
      # stack[-1] := i in the problem description.
      while stack and prices[stack[-1]] >= price:
        ans[stack.pop()] -= price
      stack.append(i)

    return ans