Restore The Array

Solution For Restore The Array

Problem Statement:
You are given an integer array nums and an integer k. In one operation, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.

Return the minimum number of operations needed to make all the elements of nums equal.

Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 1
Explanation: Increment nums[3] to make nums = [1,2,3,5].
Example 2:
Input: nums = [3,1,3,1,5], k = 7
Output: 2
Explanation: Increment nums[0] to make nums = [4,1,3,1,5]. Increment nums[3] to make nums = [4,1,3,2,5].
The minimum number of operations is 2.

Approach:
We need to make all the elements of the given array equal using minimum number of operations. For this, we would require an understanding of both the input array nums as well as the target array which we hope to achieve. An observation that can be made is that if we know the target array, then we can find the number of operations required by simply iterating over each element of the input array and adding the difference between the current element and the corresponding element of the target array.

Now we need to find the target array. We need to find the target sum which is the sum of all the elements of the input array divided by the length of the input array. This tells us the value which each element of the input array should have. But, this target sum may or may not be an integer. If it is not an integer, then we would have to round it off. When we round it off, we may be left with a sum which could be either greater than or less than the original sum.

If the target sum is an integer, then we simply set it as the target array. Otherwise, we would need to account for the difference in the sum. For this, we would first fill the target array with the integer part of the target sum, and then we would increment the first ceil(sum % length) elements by 1 (since we rounded up the target sum).

Code:

class Solution {
public:
int minOperations(vector& nums, int k) {
int n = nums.size(), targetSum = 0, i = 0, j = n – 1, ans = 0;
vector target(n, 0);
for(int i = 0; i < n; i++) targetSum += nums[i];
targetSum /= n;

    while(i < j) target[i] = target[j--] = targetSum;

    if(n % 2 == 1) target[i++] = targetSum;

    int lower = 0, upper = 0;
    for(int i = 0; i < n; i++){
        if(nums[i] < target[i]) lower += (target[i] - nums[i]);
        else upper += (nums[i] - target[i]);
    }

    while(lower > 0){
        int diff = min(k, lower);
        lower -= diff;
        target[n/2] -= diff;
        ans += diff;
    }

    while(upper > 0){
        int diff = min(k, upper);
        upper -= diff;
        target[n/2] += diff;
        ans += diff;
    }
    return ans;
}

};

Time Complexity: O(nlogn)
Space Complexity: O(n)

Step by Step Implementation For Restore The Array

public class Solution {
    public int numberOfArrays(String s, int k) {
        int n = s.length();
        int MOD = 1_000_000_007;
        long[] dp = new long[n+1];
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            long num = 0;
            for (int j = i; j >= 1; j--) {
                num = num * 10 + s.charAt(j-1) - '0';
                if (num > k) break;
                if (s.charAt(j-1) == '0') break;
                dp[i] = (dp[i] + dp[j-1]) % MOD;
            }
        }
        return (int) dp[n];
    }
}
def restore_the_array(n, k, arr): 

# n is the size of the array 
# k is the number to be added to the array 
# arr is the array 

# Initialize an empty array to store the results 

result = [] 

# Iterate over the array 

for i in range(n): 

# Check if the current element is less than k 

if arr[i] < k: 

# Append the difference between k and the current element to the result array 

result.append(k - arr[i]) 

# Otherwise, append 0 to the result array 

else: 

result.append(0) 

# Return the result array 

return result
/**
 * @param {number} n
 * @param {number} k
 * @return {number}
 */
var numberOfArrays = function(n, k) {
    // dp[i][j] means the number of ways to restore the array using the first i numbers and the largest number is j.
    // Base case: dp[0][0] = 1
    let dp = new Array(n + 1).fill(null).map(() => new Array(k + 1).fill(0));
    dp[0][0] = 1;
    
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= k; j++) {
            // If the current number is larger than j, we can't use it.
            if (num[i - 1] > j) {
                dp[i][j] = dp[i - 1][j];
            } else {
                // Otherwise, we can either use the current number or not.
                // If we use the current number, the largest number we can get is j.
                // If we don't use the current number, the largest number remains the same as dp[i - 1][j].
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num[i - 1]];
            }
        }
    }
    
    return dp[n][k];
};
int numberOfSteps (int num) {
    int count = 0;
    while (num != 0) {
        if (num % 2 == 0) {
            num /= 2;
        } else {
            num -= 1;
        }
        count++;
    }
    return count;
}
using System; 

public class Solution { 

public int NumberOfArrays(string s, int k) { 

// Base case 

if (s == null || s.Length == 0) { 

return 0; 

} 

int n = s.Length; 

// dp[i] is the number of ways to decode s[i..n-1] 

int[] dp = new int[n]; 

dp[n - 1] = s[n - 1] == '0' ? 0 : 1; 

// Fill dp in reverse order 

for (int i = n - 2; i >= 0; i--) { 

// If the current character is non-zero 

if (s[i] != '0') { 

// Consider the case when the current digit is used 

// as a single digit number 

dp[i] += dp[i + 1]; 

// Consider the case when the current digit is used 

// as a double digit number 

if (int.Parse(s.Substring(i, 2)) <= k) { 

dp[i] += i + 2 < n ? dp[i + 2] : 1; 

} 

} 

} 

return dp[0]; 

} 

}
Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]