1475. Final Prices With a Special Discount in a Shop #969
-
Topics: You are given an integer array There is a special discount for items in the shop. If you buy the Return an integer array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to apply a special discount based on the condition that there is a later item with a price less than or equal to the current price, we can use a brute-force approach. We'll iterate over the Approach:
Let's implement this solution in PHP: 1475. Final Prices With a Special Discount in a Shop <?php
function finalPrices($prices) {
$n = count($prices);
$answer = $prices; // Initialize answer array with the original prices
$stack = [];
for ($i = 0; $i < $n; $i++) {
// While the stack is not empty and the current price is less than or equal to the price at the top of the stack
while (!empty($stack) && $prices[$stack[count($stack) - 1]] >= $prices[$i]) {
$index = array_pop($stack); // Pop the index from the stack
$answer[$index] = $prices[$index] - $prices[$i]; // Apply the discount
}
array_push($stack, $i); // Push the current index onto the stack
}
return $answer;
}
// Example usage:
$prices1 = [8, 4, 6, 2, 3];
$prices2 = [1, 2, 3, 4, 5];
$prices3 = [10, 1, 1, 6];
print_r(finalPrices($prices1)); // Output: [4, 2, 4, 2, 3]
print_r(finalPrices($prices2)); // Output: [1, 2, 3, 4, 5]
print_r(finalPrices($prices3)); // Output: [9, 0, 1, 6]
?> Explanation:
Complexity:
Example Outputs:
This approach will work within the constraints of the problem ( |
Beta Was this translation helpful? Give feedback.
We need to apply a special discount based on the condition that there is a later item with a price less than or equal to the current price, we can use a brute-force approach. We'll iterate over the
prices
array and, for each item, look for the first item with a lower or equal price after it. This can be achieved with nested loops. We can utilize a stack to efficiently keep track of the items' prices and apply the special discount.Approach:
Stack Approach: