All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2501_2600.s2517_maximum_tastiness_of_candy_basket.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g2501_2600.s2517_maximum_tastiness_of_candy_basket;

// #Medium #Array #Sorting #Binary_Search #2023_04_18_Time_38_ms_(100.00%)_Space_51.8_MB_(53.92%)

import java.util.Arrays;

/**
 * 2517 - Maximum Tastiness of Candy Basket\.
 *
 * Medium
 *
 * You are given an array of positive integers `price` where `price[i]` denotes the price of the ith candy and a positive integer `k`.
 *
 * The store sells baskets of `k` **distinct** candies. The **tastiness** of a candy basket is the smallest absolute difference of the **prices** of any two candies in the basket.
 *
 * Return _the **maximum** tastiness of a candy basket._
 *
 * **Example 1:**
 *
 * **Input:** price = [13,5,1,8,21,2], k = 3
 *
 * **Output:** 8
 *
 * **Explanation:** Choose the candies with the prices [13,5,21]. 
 *
 * The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8. 
 *
 * It can be proven that 8 is the maximum tastiness that can be achieved.
 *
 * **Example 2:**
 *
 * **Input:** price = [1,3,1], k = 2
 *
 * **Output:** 2
 *
 * **Explanation:** Choose the candies with the prices [1,3]. 
 *
 * The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2. 
 *
 * It can be proven that 2 is the maximum tastiness that can be achieved.
 *
 * **Example 3:**
 *
 * **Input:** price = [7,7,7,7], k = 2
 *
 * **Output:** 0
 *
 * **Explanation:** Choosing any two distinct candies from the candies we have will result in a tastiness of 0.
 *
 * **Constraints:**
 *
 * *   2 <= k <= price.length <= 105
 * *   1 <= price[i] <= 109
**/
public class Solution {
    public int maximumTastiness(int[] price, int k) {
        Arrays.sort(price);
        int n = price.length;
        int left = 1;
        int right = (price[n - 1] - price[0]) / (k - 1) + 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (check(mid, price, k)) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left - 1;
    }

    private boolean check(int target, int[] price, int k) {
        int count = 1;
        int x0 = price[0];
        for (int x : price) {
            if (x >= x0 + target) {
                count++;
                if (count >= k) {
                    return true;
                }
                x0 = x;
            }
        }
        return false;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy