Open In App

Minimum replacements required to make sum of all K-length subarrays equal

Last Updated : 13 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N positive integers and an integer K, the task is to make the sum of all K-length subarrays equal by replacing minimum number of array elements with any integer.

Examples:

Input: arr[] = {3, 4, 3, 5, 6}, K = 2
Output: 2
Explanation: 
Operation 1: Replacing arr[3] by 4 modifies arr[] to {3, 4, 3, 4, 6}.
Operation 2: Replacing arr[4] by 3 modifies arr[] to {3, 4, 3, 4, 3}.
All subarrays of length 2 are {{3, 4}, {4, 3}, {3, 4}, {4, 3}}. Sum of all these subarrays is 7. Therefore, the minimum number of operations required is 2.

Input: arr[] = {1, 2, 3, 1, 2}, K = 3
Output: 0
Explanation: All subarrays of length 3 are {{1, 2, 3}, {2, 3, 1}, {3, 1, 2}}. Since all these subarrays have sum 6, the number of operations required is 0.

Approach: The idea is based on the observation that all subarrays will have equal sum, when all elements separated by distance K are equal.

Therefore, the problem can be solved by counting the frequency of elements separated by a distance K and find the number which appears maximum times. Follow the steps below to solve the problem:

  • Initialize a variable ans to store the required result.
  • Iterate in the range [0, K-1] using the variable i
    • Create a map, freq to store the frequency of elements separated by a distance K starting from i.
    • Traverse the map and find the element which occurs the maximum number of times.
    • Again, traverse the map and if the element is not equal to the maximum occurring element then add its frequency to the ans.
  • Print the value of ans as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number of
// operations required to make sum of
// all subarrays of size K equal
void findMinOperations(int arr[],
                       int N, int K)
{
    // Stores number of operations
    int operations = 0;
 
    // Iterate in the range [0, K-1]
    for (int i = 0; i < K; i++) {
 
        // Stores frequency of elements
        // separated by distance K
        unordered_map<int, int> freq;
 
        for (int j = i; j < N; j += K)
            freq[arr[j]]++;
 
        // Stores maximum frequency
        // and corresponding element
        int max1 = 0, num;
 
        // Find max frequency element
        // and its frequency
        for (auto x : freq) {
            if (x.second > max1) {
                max1 = x.second;
                num = x.first;
            }
        }
 
        // Update the number of operations
        for (auto x : freq) {
            if (x.first != num)
                operations += x.second;
        }
    }
 
    // Print the result
    cout << operations;
}
 
// Driver Code
int main()
{
    // Given Input
    int arr[] = { 3, 4, 3, 5, 6 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findMinOperations(arr, N, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.lang.*;
import java.util.*;
 
class GFG
{
   
  // Function to find minimum number of
  // operations required to make sum of
  // all subarrays of size K equal
  static void findMinOperations(int arr[],
                                int N, int K)
  {
 
    // Stores number of operations
    int operations = 0;
 
    // Iterate in the range [0, K-1]
    for (int i = 0; i < K; i++) {
 
      // Stores frequency of elements
      // separated by distance K
      Map<Integer, Integer> freq=new HashMap<>();
 
      for (int j = i; j < N; j += K)
        freq.put(arr[j], freq.getOrDefault(arr[j],0)+1);
 
      // Stores maximum frequency
      // and corresponding element
      int max1 = 0, num=-1;
 
      // Find max frequency element
      // and its frequency
      for (Map.Entry<Integer,Integer> x : freq.entrySet()) {
        if (x.getValue() > max1) {
          max1 = x.getValue();
          num = x.getKey();
        }
      }
 
      // Update the number of operations
      for ( Map.Entry<Integer,Integer> x : freq.entrySet()) {
        if (x.getKey() != num)
          operations += x.getValue();
      }
    }
 
    // Print the result
    System.out.print(operations);
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given Input
    int arr[] = { 3, 4, 3, 5, 6 };
    int K = 2;
    int N = arr.length;
 
    // Function Call
    findMinOperations(arr, N, K);
  }
 
}
 
// This code is contributed by offbeat


Python3




# python 3 program for the above approach
 
# Function to find minimum number of
# operations required to make sum of
# all subarrays of size K equal
def findMinOperations(arr, N, K):
    # Stores number of operations
    operations = 0
 
    # Iterate in the range [0, K-1]
    for i in range(K):
        # Stores frequency of elements
        # separated by distance K
        freq = {}
 
        for j in range(i,N,K):
            if arr[j] in freq:
                freq[arr[j]] += 1
            else:
                freq[arr[j]] = 1
 
        # Stores maximum frequency
        # and corresponding element
        max1 = 0
        num = 0
 
        # Find max frequency element
        # and its frequency
        for key,value in freq.items():
            if (value > max1):
                max1 = value
                num = key
 
        # Update the number of operations
        for key,value in freq.items():
            if (key != num):
                operations += value
 
    # Print the result
    print(operations)
 
# Driver Code
if __name__ == '__main__':
   
    # Given Input
    arr = [3, 4, 3, 5, 6]
    K = 2
    N = len(arr)
 
    # Function Call
    findMinOperations(arr, N, K)
     
    # This code is contributed by ipg2016107.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to find minimum number of
// operations required to make sum of
// all subarrays of size K equal
static void findMinOperations(int []arr,
                              int N, int K)
{
     
    // Stores number of operations
    int operations = -1;
 
    // Iterate in the range [0, K-1]
    for(int i = 0; i < K; i++)
    {
         
        // Stores frequency of elements
        // separated by distance K
        Dictionary<int,
                   int> freq = new Dictionary<int,
                                              int>();
                                               
        for(int j = i; j < N; j += K)
        {
            if (freq.ContainsKey(arr[j]))
                freq[arr[j]]++;
            else
                freq.Add(arr[j], 1);
        }
 
        // Stores maximum frequency
        // and corresponding element
        int max1 = -1, num = 0;
 
        // Find max frequency element
        // and its frequency
        foreach(KeyValuePair<int, int> entry in freq)
        {
            if (entry.Key > max1)
            {
                max1 = entry.Value;
                num = entry.Key;
            }
        }
     
        // Update the number of operations
        foreach(KeyValuePair<int, int> entry in freq)
        {
            if (entry.Key != num)
                operations += entry.Value;
        }
    }
 
    // Print the result
    Console.Write(operations);
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    int []arr = { 3, 4, 3, 5, 6 };
    int K = 2;
    int N = arr.Length;
 
    // Function Call
    findMinOperations(arr, N, K);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find minimum number of
// operations required to make sum of
// all subarrays of size K equal
function findMinOperations(arr, N, K)
{
    // Stores number of operations
    var operations = 0;
     
    var i,j;
    // Iterate in the range [0, K-1]
    for (i = 0; i < K; i++) {
 
        // Stores frequency of elements
        // separated by distance K
        var freq = new Map();
 
        for(j = i; j < N; j += K){
            if(freq.has(arr[j]))
             freq.set(arr[j], freq.get(arr[j])+1);
            else
             freq.set(arr[j],1);
        }
 
        // Stores maximum frequency
        // and corresponding element
        var max1 = 0, num;
 
        // Find max frequency element
        // and its frequency
 
        for (const [key, value] of freq.entries()) {
          if (value > max1) {
                max1 = value;
                num = key;
            }
        }
 
        // Update the number of operations
       for (const [key, value] of freq.entries()) {
            if (key != num)
                operations += value;
        }
    }
 
    // Print the result
    document.write(operations);
}
 
// Driver Code
 
    // Given Input
    var arr = [3, 4, 3, 5, 6];
    var K = 2;
    var N = arr.length;
 
    // Function Call
    findMinOperations(arr, N, K);
 
</script>


Output: 

2

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Similar Reads

Count of replacements required to make the sum of all Pairs of given type from the Array equal
Given an integer array arr of length N and an integer K, the task is to find the number of array elements to be replaced by a value from the range [1, K] such that each pair (arr[i], arr[N - 1 - i] have equal sum. Examples : Input: arr[] = {1, 2, 2, 1}, K = 3 Output: 1 Explanation: Replace arr[0] with 3, so that the array becomes {3, 2, 2, 1}. Now,
12 min read
Minimize replacements of leftmost largest array element required to make all array elements equal
Given an array arr[] consisting of N integers, the task is to make all array elements equal by replacing the leftmost largest element of the array with the largest element strictly smaller than the current maximum minimum number of times. Examples: Input: arr[] = { 1, 1, 2, 2, 3&lt;}Output: 4Explanation: Following operations reduces the required nu
6 min read
Queries to replace subarrays by equal length arrays with at most P replacements allowed for any array element
Given an array, arr[] of size N, an integer P and a 2D array Q[][] consisting of queries of the following type: 1 L R B[R - L + 1]: The task for this query is to replace the subarray {arr[L], ... arr[R] with the array B[] b given that any array element can be replaced at most P times.2 X: The task for this query is to print arr[X]. Examples: Input:
21 min read
Minimize flips on K-length subarrays required to make all array elements equal to 1
Given a binary array arr[] of size N and a positive integer K, the task is to find the minimum number of times any subarray of size K from the given array arr[] is required to be flipped to make all array elements equal to 1. If it is not possible to do so, then print "-1". Examples: Input: arr[] = {0, 1, 0}, K = 1Output: 2Explanation:Perform the o
17 min read
Minimum replacements required to make given Matrix palindromic
Given a matrix with N rows and M columns, the task is to find the minimum replacements required to make all rows and columns of a given matrix palindromic. Examples: Input: a[][] = {{1, 2, 3}, {4, 5, 3}, {1, 2, 1}}Output: 2Explanation: To make the given matrix palindromic, replace a[0][2] by 1 and replace a[1][2] by 4. Input: a[][] = {{1, 2, 4}, {4
10 min read
Minimum replacements with real numbers required to make given Array AP
Given an array arr[] of N integers. The task is to convert the array into an Arithmetic Progression with the minimum number of replacements possible. In one replacement any one element can be replaced by any real number. Examples: Input: N = 6, arr[] = { 3, -2, 4, -1, -4, 0 }Output: 3Explanation: Change arr[0] = -2.5, arr[2] = -1.5, arr[4] = -0.5So
7 min read
Minimize replacements by previous or next alphabet required to make all characters of a string the same
Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations required to make all the characters of the string S the same. In each operation, choose any character and replace it with its next or previous alphabet. Note: The alphabets are considered to be cyclic i.e., Next character of z is con
6 min read
Make sum of all subarrays of length K equal by only inserting elements
Given an array arr[] of length N such that (1 &lt;= arr[i] &lt;= N), the task is to modify the array, by only inserting elements within the range [1, N], such that the sum of all subarrays of length K become equal. Print the modified array, if possible. Else print "Not possible".Examples: Input: arr[] = {1, 2, 2, 1}, K = 2 Output: 1 2 1 2 1 Explana
7 min read
Minimize replacements by integers up to K to make the sum of equidistant array elements from the end equal
Given an array arr[] of even length N and an integer K, the task is to minimize the count of replacing array elements by an integer from the range [1, K] such that the sum of all pair of equidistant elements from the end of the array is equal. Examples: Input: arr[] = {1, 2, 4, 3}, K = 4Output: 1Explanation:Replacing arr[2] by 2 modifies arr[] to {
9 min read
Minimize replacements with values up to K to make sum of two given arrays equal
Given a positive integer K and two arrays A[] and B[] consisting of M and N positive integers from the range [1, K] respectively, the task is to minimize the count of replacements of array elements by values from the range [1, K] such that the sum of elements of both the arrays becomes equal. If it is impossible to make the sum equal, then print -1
15 min read