Final Prices With a Special Discount in a Shop

Final Prices With a Special Discount in a Shop

You are given an integer array prices where prices[i] is the price of the i<sup>th</sup> item in a shop.

There is a special discount for items in the shop. If you buy the i<sup>th</sup> item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.

Return an integer array answer where answer[i] is the final price you will pay for the i<sup>th</sup> item of the shop, considering the special discount.

LeetCode Problem - 1475

class Solution {
    // Function to calculate final prices after discount
    public int[] finalPrices(int[] prices) {
        int[] result = new int[prices.length]; // Array to store final prices

        for(int i=0; i<prices.length; i++){ // Loop through the prices array
            boolean flag = true; // Flag to check if a discount is applied
            for(int j=i+1; j<prices.length; j++){ // Check prices ahead
                if(prices[j] <= prices[i]){ // If a lower or equal price is found
                    int discount = prices[i] - prices[j]; // Calculate the discount
                    result[i] = discount; // Assign the discount as the final price
                    flag = false; // Discount applied, set flag to false
                    break; // Exit the loop
                }
            }
            if(flag){ // If no discount was applied
                result[i] = prices[i]; // Assign the original price as final price
            }
        }
        return result; // Return the array of final prices
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!