Open In App

Smallest value of k in matrix by decreasing value

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix mat[][] of dimensions m x n, and two positive integer ‘x’ and ‘y’. You can perform at least ‘x‘ operations on the matrix. In each operation, you can choose any cell in the matrix and decrease its value at most ‘y‘. The task is to determine the smallest value of k, where k >= 0. The value k is the difference between the maximum and minimum values in the matrix.

Examples:

Input: mat = { { 1, 4, 7 }, { 3, 2, 6 }, { 11, 4, 12 } }, x = 3, y = 1
Output: 9
Explanation: Decrement 12 two times and 11 one time then the maximum element will be 10 and the minimum element will be 1. so the smallest value of k is 9.

Input: mat = {{1, 10}}, x = 10, y = 2
Output: 0
Explanation: 10 can be reduce to 0 in 5 operation and 1 will reduce to 0 in one operation. so the smallest value of k is 0.

Approach:

The idea is to use Binary search on answer here to efficiently find the minimum value (the maximum value to minimize) by iteratively limiting down the range of possible values. We start with the range between the minimum and maximum values in the matrix and repeatedly check if the midpoint is possible within x operations. If it is, we update our result and reduce the upper bound; if not, we adjust the lower bound. This process continues until we’ve identified the minimum possible value.

Steps-by-step approach:

  • Create variables start and end to find the initial range for the binary search. Set the end to the maximum value in the matrix.
  • Create a result variable to end since initially, the maximum value is the upper bound of the possible range.
  • Use the binary search until start <= end.
    • Calculate the mid between the start and end.
    • Use the isValid() function to check if mid can be achieved within x operations. If it can, update the result to mid and contract the search range by setting the end to mid-1.
    • If mid is not achievable within x operations, adjust the search range by setting start to mid + 1.
  • The final result will be the minimum achievable value within x operations.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits> // Include the header for INT_MAX

using namespace std;

int m, n;

// Function to check if it's possible to achieve a value
// 'val' within 'x' operations
bool isValid(int val, int x, int y, vector<vector<int>> &mat)
{
    int operationRequire = 0;

    // Iterate through the 2D array elements
    for (int i = 0; i < mat.size(); i++) {
        for (int j = 0; j < mat[0].size(); j++) {
            if (mat[i][j] > val)
                operationRequire += ceil(((double) mat[i][j] - (double) val) / y);

            // If operations required exceed 'x', it's not
            // possible
            if (operationRequire > x)
                return false;
        }
    }

    // It's possible to achieve 'val' within 'x' operations
    return true;
}

// Function to minimize the maximum value by adjusting the
// 2D array
int minimizeMax(int x, int y, vector<vector<int>> &mat)
{

    int start = 0, end = 0, minn = INT_MAX;

    // Find the maximum value in the 2D array initially
    for (auto i : mat) {
        end = max(end, *max_element(i.begin(), i.end()));
        minn = min(minn, *min_element(i.begin(), i.end()));
    }

    int result = end;

    // Binary search to find the minimum value that can be
    // achieved
    while (start <= end) {
        int mid = (start + end) / 2;

        // Check if 'mid' is achievable within 'x'
        // operations
        if (isValid(mid, x, y, mat)) {
            result = mid;
            end = mid - 1;
        }
        else {
            start = mid + 1;
        }
    }

    // Return the difference between minimum possible
    // maximum value and minimum value
    return max(result - minn, 0);
}

int main()
{

    // Example input 2D array
    vector<vector<int>> mat
        = { { 1, 4, 7 }, { 3, 2, 6 }, { 11, 4, 12 } };

    int x = 3, y = 1;

    // Find the smallest maximum value of K
    int maxValue = minimizeMax(x, y, mat);

    // Print the result
    cout << "The smallest maximum value is: " << maxValue;

    return 0;
}
Java
import java.util.Arrays;

public class MinimizeMaxValue {

    static int m, n;

    // Function to check if it's possible to achieve a value
    // 'val' within 'x' operations
    static boolean isValid(int val, int x, int y, int[][] mat) {
        int operationRequire = 0;

        // Iterate through the 2D array elements
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (mat[i][j] > val)
                    operationRequire += Math.ceil(((double) mat[i][j] - (double) val) / y);

                // If operations required exceed 'x', it's not possible
                if (operationRequire > x)
                    return false;
            }
        }

        // It's possible to achieve 'val' within 'x' operations
        return true;
    }

    // Function to minimize the maximum value by adjusting the
    // 2D array
    static int minimizeMax(int x, int y, int[][] mat) {

        int start = 0, end = 0, minn = Integer.MAX_VALUE;

        // Find the maximum value in the 2D array initially
        for (int[] i : mat) {
            end = Math.max(end, Arrays.stream(i).max().orElse(0));
            minn = Math.min(minn, Arrays.stream(i).min().orElse(Integer.MAX_VALUE));
        }

        int result = end;

        // Binary search to find the minimum value that can be achieved
        while (start <= end) {
            int mid = (start + end) / 2;

            // Check if 'mid' is achievable within 'x' operations
            if (isValid(mid, x, y, mat)) {
                result = mid;
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }

        // Return the difference between the minimum possible maximum value and minimum value
        return Math.max(result - minn, 0);
    }

    public static void main(String[] args) {
        // Example input 2D array
        int[][] mat = { { 1, 4, 7 }, { 3, 2, 6 }, { 11, 4, 12 } };

        int x = 3, y = 1;

        // Find the smallest maximum value of K
        int maxValue = minimizeMax(x, y, mat);

        // Print the result
        System.out.println("The smallest maximum value is: " + maxValue);
    }
}

// This code is contributed by rambabuguphka
C#
//code by flutterfly
using System;
using System.Collections.Generic;
using System.Linq;

public class GFG
{
    // Function to check if it's possible to achieve a value
    // 'val' within 'x' operations
    static bool IsValid(int val, int x, int y, List<List<int>> mat)
    {
        int operationRequire = 0;

        // Iterate through the 2D array elements
        foreach (var row in mat)
        {
            foreach (var element in row)
            {
                if (element > val)
                    operationRequire += (int)Math.Ceiling((double)(element - val) / y);

                // If operations required exceed 'x', it's not possible
                if (operationRequire > x)
                    return false;
            }
        }

        // It's possible to achieve 'val' within 'x' operations
        return true;
    }

    // Function to minimize the maximum value by adjusting the
    // 2D array
    static int MinimizeMax(int x, int y, List<List<int>> mat)
    {
        int start = 0, end = 0, minn = int.MaxValue;

        // Find the maximum value in the 2D array initially
        foreach (var row in mat)
        {
            end = Math.Max(end, row.Max());
            minn = Math.Min(minn, row.Min());
        }

        int result = end;

        // Binary search to find the minimum value that can be
        // achieved
        while (start <= end)
        {
            int mid = (start + end) / 2;

            // Check if 'mid' is achievable within 'x' operations
            if (IsValid(mid, x, y, mat))
            {
                result = mid;
                end = mid - 1;
            }
            else
            {
                start = mid + 1;
            }
        }

        // Return the difference between minimum possible
        // maximum value and minimum value
        return Math.Max(result - minn, 0);
    }

    static void Main(string[] args)
    {
        // Example input 2D array
        List<List<int>> mat = new List<List<int>>
        {
            new List<int> {1, 4, 7},
            new List<int> {3, 2, 6},
            new List<int> {11, 4, 12}
        };

        int x = 3, y = 1;

        // Find the smallest maximum value of K
        int maxValue = MinimizeMax(x, y, mat);

        // Print the result
        Console.WriteLine("The smallest maximum value is: " + maxValue);
    }
}
JavaScript
// Function to check if it's possible to achieve a value
// 'val' within 'x' operations
function isValid(val, x, y, mat) {
    let operationRequire = 0;

    // Iterate through the 2D array elements
    for (let i = 0; i < mat.length; i++) {
        for (let j = 0; j < mat[0].length; j++) {
            if (mat[i][j] > val)
                operationRequire += Math.ceil((mat[i][j] - val) / y);

            // If operations required exceed 'x', it's not
            // possible
            if (operationRequire > x)
                return false;
        }
    }

    // It's possible to achieve 'val' within 'x' operations
    return true;
}

// Function to minimize the maximum value by adjusting the
// 2D array
function minimizeMax(x, y, mat) {

    let start = 0, end = 0, minn = Number.MAX_SAFE_INTEGER;

    // Find the maximum value in the 2D array initially
    for (let i of mat) {
        end = Math.max(end, Math.max(...i));
        minn = Math.min(minn, Math.min(...i));
    }

    let result = end;

    // Binary search to find the minimum value that can be
    // achieved
    while (start <= end) {
        let mid = Math.floor((start + end) / 2);

        // Check if 'mid' is achievable within 'x'
        // operations
        if (isValid(mid, x, y, mat)) {
            result = mid;
            end = mid - 1;
        }
        else {
            start = mid + 1;
        }
    }

    // Return the difference between minimum possible
    // maximum value and mininmum value
    return Math.max(result - minn, 0);
}

// Example input 2D array
let mat = [ [ 1, 4, 7 ], [ 3, 2, 6 ], [ 11, 4, 12 ] ];

let x = 3, y = 1;

// Find the smallest maximum value of K
let maxValue = minimizeMax(x, y, mat);

// Print the result
console.log("The smallest maximum value is: " + maxValue);
Python3
import math

# Function to check if it's possible to achieve a value
# 'val' within 'x' operations
def is_valid(val, x, y, mat):
    operation_require = 0

    # Iterate through the 2D array elements
    for row in mat:
        for element in row:
            if element > val:
                operation_require += math.ceil((element - val) / y)

            # If operations required exceed 'x', it's not
            # possible
            if operation_require > x:
                return False

    # It's possible to achieve 'val' within 'x' operations
    return True

# Function to minimize the maximum value by adjusting the
# 2D array
def minimize_max(x, y, mat):
    start = 0
    end = 0
    minn = float('inf')

    # Find the maximum value in the 2D array initially
    for row in mat:
        end = max(end, max(row))
        minn = min(minn, min(row))

    result = end

    # Binary search to find the minimum value that can be
    # achieved
    while start <= end:
        mid = (start + end) // 2

        # Check if 'mid' is achievable within 'x'
        # operations
        if is_valid(mid, x, y, mat):
            result = mid
            end = mid - 1
        else:
            start = mid + 1

    # Return the difference between minimum possible
    # maximum value and minimum value
    return max(result - minn, 0)

# Example input 2D array
mat = [[1, 4, 7], [3, 2, 6], [11, 4, 12]]
x = 3
y = 1

# Find the smallest maximum value of K
max_value = minimize_max(x, y, mat)

# Print the result
print("The smallest maximum value is:", max_value)

Output

The smallest maximum value is: 9

Time Complexity: O(m * n * log(Max), where m is the number of rows and n is the number of columns of matrix and Max is the maximum element in matrix
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads