Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2439. Minimize Maximum of Array

Explanation

To solve this problem, we need to find the minimum possible value of the maximum integer in the array nums after performing a series of operations where we decrease an element at index i by 1 and increase the element at index i-1 by 1. The key insight is that the maximum integer in the array will decrease by at least 1 in each operation.

Therefore, to minimize the maximum integer, we need to distribute the excess values from larger elements to smaller elements in an optimal way. We can achieve this by iterating through the array and performing operations whenever we encounter a value that is greater than the value on its left.

The algorithm involves iterating through the array and performing the operations as described above until we reach a point where no more operations can be performed. The minimum possible value of the maximum integer will be the maximum value in the array at that point.

Time Complexity: O(n) where n is the length of the input array nums. Space Complexity: O(1)

class Solution {
    public int minimizeMax(int[] nums) {
        int max = nums[0];
        int n = nums.length;
        
        for (int i = 1; i < n; i++) {
            if (nums[i] > nums[i - 1]) {
                int diff = nums[i] - nums[i - 1];
                max = Math.max(max, nums[i]);
                nums[i] -= diff;
                nums[i - 1] += diff;
            }
        }
        
        return max;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.