Binary Search To Find An Answer

public int findDuplicate(int[] nums) {
    int lo = 1, hi = nums.length - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (findSmall(nums, mid)) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    return lo;
}

private boolean findSmall(int[] nums, int target) {
    int count = 0;
    for (int num : nums) {
        if (num <= target) {
            count++;
        }
    }
    return count <= target;
}

For problems such as 410, 875, 1011, 1231, it is hard to start. It has pre-conditions:

  • Choose data from an array

  • Must choose consecutively

  • Can be determined by "try out"

  • Asking for a "min" or "max" of the choice

The problem asks if can be divide the array by a number and having the min/max of this range. Search in a range between the max of all numbers and the sum of all numbers. Use a helper function to try all numbers of the range, and find the min/max.

Instead of trying all numbers, we can use binary search to quickly determine the result.

T: O(N*log(range_size)) S: O(1)

Divide the array into K continuous subarrays, maximize the min share of this array

Find the Smallest Divisor Given a Threshold

Divide Chocolate

424. Longest Repeating Character Replacementarrow-up-right

1802. Maximum Value at a Given Index in a Bounded Arrayarrow-up-right

2616. Minimize the Maximum Difference of Pairsarrow-up-right

(NOT on LC) Maximum min absolute difference

Problem: Given an integer array nums and an integer d, you can adjust each element of nums by adding any value up to d (including zero). Your goal is to modify the array such that the minimum absolute difference between any two elements in the adjusted array is maximized. Example: Given nums = [6, 0, 3] and d = 2, one possible adjusted array is [8, 0, 4]. The minimum absolute difference among these elements is 4 (the minimum of |8−4|, |4−0|, and |8−0|). Therefore, the maximum achievable minimum difference is 4. Given nums = [1, 5, 9, 14] and d = 3, you can adjust each element by adding any value from 0 up to 3. One possible adjusted array is [4, 5, 9, 14]. The pairwise absolute differences are: |4 - 5| = 1 |5 - 9| = 4 |9 - 14| = 5 and others like |4 - 9| = 5, |5 - 14| = 9, |4 - 14| = 10 The minimum difference here is 1. But adjusting to [1, 5, 12, 14] gives differences: |1 - 5| = 4 |5 - 12| = 7 |12 - 14| = 2 others: |1 - 12| = 11, |1 - 14| = 13, |5 - 14| = 9

The minimum difference is now 2, which is larger than before. Your goal is to find such adjustments that maximize this minimum absolute difference.

274. H-Indexarrow-up-right

Last updated