Spend Required for Gift Card
There are n products begin sold on the Amazon Online shopping app. The price of the ithproduct is price[i]. The developers at Amazon decided to give special gift cards to innovative customers. A gift card will be given if any customer buys a contiguous subsegment of products and at least 2 of the products have a matching price. Find the minimum amount of money a customer needs to spend in order to get the gift card. If is is not possible for any customer to get a gift card, return -1.
Constraints 02 1 <= n <= 5 . 10 ^ 5 1 <= price[i] <= 10 ^ 6, 0 <= i < n Samples 02 assert(findMinimumPrice([1, 2, 3, 1, 2, 1]) == 4) assert(findMinimumPrice([1, 2, 1, 2]) == 4) assert(findMinimumPrice([1, 100, 1, 7, 7]) == 14)
Here is an optimized Python solution to find the minimum price needed to get a gift card based on the problem constraints:
|
|
The key optimizations are:
- Store prefix sums to efficiently compute range sums
- Use a set to check for 2+ matching prices
- Minimize comparisons needed
This reduces the runtime to O(n^2) while keeping O(n) space complexity.
The most optimal solution for this problem of finding the minimum price for a gift card with matching prices in O(n) time complexity is:
|
|
The key ideas are:
Use a hashmap to track the last index of each seen price
When a duplicate price is found, calculate segment price using stored index
This avoids nested loops, reducing time to O(n)
Space complexity is O(n) for the hashmap
By tracking last duplicate indices, we can linearly scan and immediately compute matching segment prices when a duplicate is found. This algorithm optimization avoids the quadratic nested loop solution.