1475. Final Prices With a Special Discount in a Shop
Difficulty: Easy
Topics: Array, Stack, Monotonic Stack
You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith 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 ith item of the shop, considering the special discount.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
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.
Stack Approach:
Edge Case: If no item has a smaller price later in the array, no discount is applied.
Let's implement this solution in PHP: 1475. Final Prices With a Special Discount in a Shop
Explanation:
Initialization:
- Create an array $result of the same size as $prices and initialize it to 0.
Outer Loop:
- Loop through each price at index $i to calculate its final price after discounts.
Inner Loop:
- For each price $i, iterate through the subsequent prices $j (where $j > $i).
- Check if $prices[$j] is less than or equal to $prices[$i]. If true, set $discount = $prices[$j] and exit the inner loop.
Final Price Calculation:
- Subtract the found discount from $prices[$i] and store the result in $result[$i].
Return Result:
- After processing all prices, return the final result array.
Complexity:
This approach will work within the constraints of the problem (1 <= prices.length <= 500), even though it is not the most optimized solution.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Final Prices With a Special Discount in a Shop. For more information, please follow other related articles on the PHP Chinese website!