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:

  1. Sort the prices array in non-decreasing order.
  2. Initialize a variable minDiff to store the minimum difference between any two prices.
  3. Iterate over the sorted array from index 0 to n-k (n is the total number of candies).
  4. Calculate the difference between prices at current index and index k-1 ahead.
  5. Update minDiff with the minimum of current minDiff and the calculated difference.
  6. 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...