LeetCode 2371: Minimize Maximum Value in a Grid

Problem Description

Explanation

The problem asks to minimize the maximum value in a grid by performing operations. Each operation involves selecting a non-empty row or column and decrementing all the elements in that row or column by 1. The goal is to find the minimum possible maximum value that can be achieved after performing a certain number of operations.

To solve this problem, we can use binary search to find the minimum possible maximum value. We can start with a lower bound of 0 and an upper bound of the maximum value in the grid. Then, we perform a binary search on the possible values to find the minimum value such that it is possible to achieve that value or less after performing a certain number of operations.

Solutions

class Solution {
    public int minimizeMaximumValue(int[][] grid, int k) {
        int low = 0, high = 1000000;
        
        while (low < high) {
            int mid = low + (high - low) / 2;
            
            if (isPossible(grid, mid, k)) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        
        return low;
    }
    
    private boolean isPossible(int[][] grid, int target, int k) {
        int cnt = 0;
        
        for (int[] row : grid) {
            for (int num : row) {
                if (num > target) {
                    cnt += (num - target + k - 1) / k;
                }
            }
        }
        
        return cnt <= k;
    }
}

Loading editor...