LeetCode 3293: Calculate Product Final Price

Database

Problem Description

Explanation:

To solve this problem, we iterate through the array from left to right. For each element, we iterate through the subsequent elements to find the first element that is smaller than the current element. If found, we update the current element by subtracting the found element from it. If no smaller element is found, the current element remains unchanged. :

Solutions

class Solution {
    public int[] finalPrices(int[] prices) {
        for (int i = 0; i < prices.length; i++) {
            int discount = 0;
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] <= prices[i]) {
                    discount = prices[j];
                    break;
                }
            }
            prices[i] -= discount;
        }
        return prices;
    }
}

Loading editor...