Problem Description
Given an array of positive integers representing candy prices and an integer k, select k distinct candies such that the tastiness of the candy basket, defined as the smallest absolute difference between the prices of any two chosen candies, is maximized. Return the maximum possible tastiness.
Key Insights
- Sorting the array simplifies finding pairs with a desired minimum difference.
- Use binary search on the answer (the possible minimum difference) to efficiently determine the maximum tastiness.
- A greedy method can be used to check if a candidate tastiness is achievable by selecting candies that are at least the candidate difference apart.
Space and Time Complexity
Time Complexity: O(n log n + n log m) where n is the number of candies and m is the range of possible tastiness values.
Space Complexity: O(n) for sorting the array.
Solution
The solution begins by sorting the given prices array. The problem is then transformed into a decision problem where we seek to determine if k candies can be selected such that each adjacent chosen candy has a difference of at least mid, a candidate tastiness value. This check is done using a greedy algorithm that iterates over the sorted array and counts the number of candies selected given the difference constraint. Binary search is employed over the range of possible tastiness values starting from 0 to the maximum difference between the smallest and largest candy prices. The largest mid value for which the greedy test passes is the answer.