LeetCode-in-Java

2064. Minimized Maximum of Products Distributed to Any Store

Medium

You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.

You need to distribute all products to the retail stores following these rules:

Return the minimum possible x.

Example 1:

Input: n = 6, quantities = [11,6]

Output: 3

Explanation: One optimal way is:

The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.

Example 2:

Input: n = 7, quantities = [15,10,10]

Output: 5

Explanation: One optimal way is:

The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.

Example 3:

Input: n = 1, quantities = [100000]

Output: 100000

Explanation: The only optimal way is:

The maximum number of products given to any store is max(100000) = 100000.

Constraints:

Solution

public class Solution {
    public int minimizedMaximum(int n, int[] q) {
        int min = 1;
        int max = maxi(q);
        int ans = 0;
        while (min <= max) {
            int mid = min + (max - min) / 2;
            if (condition(q, mid, n)) {
                ans = mid;
                max = mid - 1;
            } else {
                min = mid + 1;
            }
        }
        return ans;
    }

    private boolean condition(int[] arr, int mid, int n) {
        int ans = 0;
        for (int num : arr) {
            ans += (num) / mid;
            if (num % mid != 0) {
                ans++;
            }
        }
        return ans <= n;
    }

    private int maxi(int[] arr) {
        int ans = 0;
        for (int n : arr) {
            ans = Math.max(ans, n);
        }
        return ans;
    }
}