짬뽕얼큰하게의 맨땅에 헤딩 :: Final Prices With a Special Discount in a Shop

Leetcode Problem:

Summary

  • Given an integer array prices where prices[i] is the price of the ith item in a shop, find the final price for each item considering a special discount.

Approach

  • The solution uses a stack to keep track of the prices of items that have not been discounted yet
  • It iterates through the prices array in reverse order, and for each item, it checks if there is a smaller item in the stack that can provide a discount
  • If a discount is found, it is applied to the current item, and the updated price is pushed onto the stack
  • If no discount is found, the current price is pushed onto the stack as is.

Complexity

  • O(n), where n is the number of items in the prices array, because each item is processed once.

Explanation

  • The solution uses a stack to efficiently find the smallest price that can provide a discount for each item
  • It starts by iterating through the prices array in reverse order, and for each item, it checks if there is a smaller item in the stack that can provide a discount
  • If a discount is found, it is applied to the current item, and the updated price is pushed onto the stack
  • This process continues until the stack is empty, at which point the current item's price is pushed onto the stack as is
  • This approach ensures that each item is processed only once and that the stack is always in the correct order to find the smallest price that can provide a discount.

Solution Code:


class Solution {
public:
    vector st;
    vector finalPrices(vector& prices) {
        for(int i = prices.size() - 1; i >= 0 ; i--){
            while(st.size() != 0 && st.back() > prices[i]){
                st.pop_back();
            }
            if(st.size() == 0){
                st.push_back(prices[i]);
            } else{
                prices[i] -= st.back();
                st.push_back(prices[i] + st.back());
            }
        }
        return prices;
    }
};

'알고리즘' 카테고리의 다른 글

Reverse Odd Levels of Binary Tree  (0) 2025.02.27
Max Chunks To Make Sorted  (0) 2025.02.27
Construct String With Repeat Limit  (0) 2025.02.27
Final Array State After K Multiplication Operations I  (0) 2025.02.27
Maximum Average Pass Ratio  (0) 2025.02.27
블로그 이미지

짬뽕얼큰하게

,