2023-04-05 Daily Challenge

Today I have done leetcode's April LeetCoding Challenge with cpp.

April LeetCoding Challenge 5

Description

Minimize Maximum of Array

You are given a 0-indexed array nums comprising of n non-negative integers.

In one operation, you must:

  • Choose an integer i such that 1 <= i < n and nums[i] > 0.
  • Decrease nums[i] by 1.
  • Increase nums[i - 1] by 1.

Return the minimum possible value of the maximum integer of nums after performing any number of operations.

 

Example 1:

Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.

Example 2:

Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.

 

Constraints:

  • n == nums.length
  • 2 <= n <= 105
  • 0 <= nums[i] <= 109

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
public:
  int minimizeArrayValue(vector<int>& nums) {
    long long sum = accumulate(nums.begin(), nums.end(), 0LL);
    double average = 1.0 * sum / nums.size();
    long long current_sum = 0;
    int answer = ceil(average);
    for(int i = 0; i < nums.size(); ++i) {
      current_sum += nums[i];
      if(average * (i + 1) < current_sum) {
        answer = max<int>(answer, (current_sum + i) / (i + 1));
      }
    }
    return answer;
  }
};

// Accepted
// 68/68 cases passed (100 ms)
// Your runtime beats 98.83 % of cpp submissions
// Your memory usage beats 99 % of cpp submissions (70.4 MB)