Minimize Maximum Of Array

Solution For Minimize Maximum Of Array

Problem Statement:

Given an array nums and a value target, return the minimum possible value of max(nums[i], nums[j], nums[k]) where i, j, and k are indices of the array and max(nums[i], nums[j], nums[k]) <= target.

Example:

Input: nums = [1,2,3,4,5,6,7,8,9], target = 10

Output: 5

Explanation: The maximum of any three numbers in the array is 9, and it is less than or equal to the target value of 10.

Solution:

This problem can be solved using binary search. We will first define the minimum and maximum possible values that the maximum value of the array can take. The minimum possible value is 0, and the maximum possible value is the largest value in the array.

We will then perform binary search on the possible range of values for the maximum value of the array. For each value that we test, we will check if there exist i, j, k such that max(nums[i], nums[j], nums[k]) is less than or equal to the current tested value. If such i, j, k exist, then we will search for a smaller value of the maximum value, otherwise we will search for a larger value.

Let’s define the function check, which will check if there exist i, j, k such that max(nums[i], nums[j], nums[k]) is less than or equal to the current tested value:

def check(nums, target, max_value):
# i, j, and k are indices of the array and max(nums[i], nums[j], nums[k]) <= max_value

count = 0
n = len(nums)
i = 0

while i < n:
    j = i + 1
    k = n - 1

    while j < k:
        if nums[i] + nums[j] + nums[k] <= max_value:
            count += k - j  # Any k greater than j will be valid
            j += 1
        else:
            k -= 1  # Reduce the value of k, so that the sum reduces

    i += 1

return count >= target

In the above function, we are using two-pointers to find all possible i, j, k such that max(nums[i], nums[j], nums[k]) is less than or equal to the current tested value. count keeps track of the number of such possible i, j, k. If it is greater than or equal to the target, then we return True, otherwise False.

Now we will use binary search to find the minimum value of max(nums[i], nums[j], nums[k]) for which check returns True:

def minimize_max(nums, target):
left = 0
right = max(nums)

while left < right:
    mid = left + (right - left) // 2

    if check(nums, target, mid):
        right = mid
    else:
        left = mid + 1

return left

In the above function, we are performing binary search on the possible range of values for the maximum value of the array. If check returns True for the mid value, then we search for a smaller value to the left of mid, otherwise we search for a larger value to the right of mid. We continue this process until left and right converge, which means we have found the minimum possible value of max(nums[i], nums[j], nums[k]).

Time Complexity:

The time complexity of this solution is O(n^2 log n), where n is the length of the array nums. The check function has a time complexity of O(n^2), as we are using two-pointers to find all possible i, j, k. We are performing binary search on the range of values from 0 to the largest value in the array, which has a time complexity of O(log n). Therefore, the overall time complexity is O(n^2 log n).

Space Complexity:

The space complexity of this solution is O(1), as we are not using any additional data structure.

Step by Step Implementation For Minimize Maximum Of Array

class Solution { 
    // Function to find minimum of maximum for  
    // every window size in an array 
    static void printMinMax(int arr[], int n) 
    { 
        // Consider all windows of different sizes starting 
        // from size 1 
        for (int k = 1; k <= n; k++) 
        { 
            // Initialize minimum of maximum for current 
            // window size k 
            int minmax = arr[0]; 
  
            // Consider all windows of size k 
            for (int i = 0; i <= n - k; i++) 
            { 
                // Find maximum of all windows of size k 
                int max = arr[i]; 
                for (int j = 1; j < k; j++) 
                { 
                    if (arr[i + j] > max) 
                        max = arr[i + j]; 
                } 
  
                // Update minmax if a minimum of maximum is 
                // found 
                if (minmax > max) 
                    minmax = max; 
            } 
  
            // Print the minimum of maximum for current 
            // window size 
            System.out.print(minmax + " "); 
        } 
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int arr[] = {10, 20, 30, 50, 10, 70, 30}; 
        int n = arr.length; 
        printMinMax(arr, n); 
    } 
}
# Python3 program to find minimum 
# maximum of an array 
  
# Returns minimum maximum of an array 
def minMax(arr, n): 
  
    minm = arr[0] 
    maxm = arr[0] 
      
    for i in range(1, n): 
        if (arr[i] > maxm): 
            maxm = arr[i] 
        if (arr[i] < minm): 
            minm = arr[i] 
              
    return (minm, maxm) 
  
# Driver Code 
arr = [1000, 11, 445, 1, 330, 3000] 
n = len(arr) 
  
minMax(arr, n)
/**
 * @param {number[]} nums
 * @return {number}
 */
var minMoves = function(nums) {
    // sort the array in ascending order
    nums.sort((a, b) => a - b);
    
    // initialize a variable to keep track of the number of moves
    let moves = 0;
    
    // iterate through the array, starting from the second element
    for (let i = 1; i < nums.length; i++) {
        // add the difference between the current element and the first element to the moves variable
        moves += nums[i] - nums[0];
    }
    
    // return the number of moves
    return moves;
};
One possible solution to the leetcode problem "minimize-maximum-of-array" is as follows:

int minimizeMaximum(vector &arr, int k) {
    int n = arr.size();
    
    // Sort the array in ascending order
    sort(arr.begin(), arr.end());
    
    // Initialize the minimum possible maximum value
    int minMax = arr[n-1];
    
    // Consider each element of the array in turn
    for (int i = 0; i < n-1; i++) {
        // If we can remove enough elements to make the
        // current element the new maximum, do so
        if (arr[i+1] - arr[i] <= k) {
            int numToRemove = n-(i+1);
            k -= numToRemove;
            arr[i+1] = arr[i];
        }
        
        // Update the minimum possible maximum value
        minMax = min(minMax, arr[i]);
    }
    
    return minMax;
}
Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B. 

class Solution {
    public int SmallestRangeII(int[] A, int K) {
        // Sort the array first
        Array.Sort(A);
        
        // Initialize minDiff to be the difference between the first and last element
        int minDiff = A[A.Length - 1] - A[0];
        
        // Iterate through the array
        for (int i = 0; i < A.Length - 1; i++) {
            // Initialize max to be the maximum of A[i] + K and A[i + 1] - K
            int max = Math.Max(A[i] + K, A[i + 1] - K);
            // Initialize min to be the minimum of A[i] + K and A[i + 1] - K
            int min = Math.Min(A[i] + K, A[i + 1] - K);
            
            // Find the difference between the maximum and minimum value
            int diff = max - min;
            
            // If the difference is smaller than the minimum difference, update minDiff
            if (diff < minDiff) {
                minDiff = diff;
            }
        }
        
        // Return the minimum difference
        return minDiff;
    }
}


Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]