Skip to content

2439. Minimize Maximum of Array

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minimizeArrayValue(vector<int>& nums) {
    long ans = 0;
    long prefix = 0;

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      const long prefixAvg = ceil(prefix / static_cast<double>(i + 1));
      ans = max(ans, prefixAvg);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int minimizeArrayValue(int[] nums) {
    long ans = 0;
    long prefix = 0;

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      final long prefixAvg = (long) Math.ceil(prefix / (double) (i + 1));
      ans = Math.max(ans, prefixAvg);
    }

    return (int) ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minimizeArrayValue(self, nums: list[int]) -> int:
    ans = 0
    prefix = 0

    for i, num in enumerate(nums):
      prefix += num
      prefixAvg = math.ceil(prefix / (i + 1))
      ans = max(ans, prefixAvg)

    return ans