LeetCode 2517: Maximum Tastiness of Candy Basket
Problem Description
Explanation:
To find the maximum tastiness of a candy basket, we need to choose k distinct candies with the smallest absolute price difference. We can achieve this by sorting the prices and then iterating over the sorted array to find the minimum difference between any two prices in a window of size k.
Algorithm:
- Sort the prices array in non-decreasing order.
- Initialize a variable
minDiff
to store the minimum difference between any two prices. - Iterate over the sorted array from index 0 to n-k (n is the total number of candies).
- Calculate the difference between prices at current index and index k-1 ahead.
- Update
minDiff
with the minimum of current minDiff and the calculated difference. - Return
minDiff
as the maximum tastiness of the candy basket.
Time Complexity: O(n log n) where n is the length of the prices array due to sorting. Space Complexity: O(1) since we are not using any extra space.
:
Solutions
class Solution {
public int maxTastiness(int[] price, int k) {
Arrays.sort(price);
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i <= price.length - k; i++) {
minDiff = Math.min(minDiff, price[i + k - 1] - price[i]);
}
return minDiff;
}
}
Loading editor...