📌  相关文章
📜  使所有 K 长度子数组的总和相等所需的最小替换

📅  最后修改于: 2021-09-07 04:53:56             🧑  作者: Mango

给定一个由N 个正整数和一个整数K组成的数组 arr[] ,任务是通过用任何整数替换最小数量的数组元素来使所有 K 长度子数组的总和相等。

例子:

方法:这个想法是基于这样一种观察,即当所有由距离K分隔的元素都相等时,所有子数组的总和都相等。

因此,可以通过计算相隔距离为K的元素出现的次数,并找出出现次数最多的个数来解决该问题。请按照以下步骤解决问题:

  • 初始化一个变量ans来存储所需的结果。
  • 在 [0, K-1]范围内迭代使用 变量i
    • 创建映射 freq 以存储从i开始的距离 K分隔的元素的频率。
    • 遍历地图并找到出现次数最多的元素。
    • 再次遍历地图 如果元素不等于最大出现元素,则将其频率添加到ans
  • 打印 ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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 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;
}


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 freq = new Dictionary();
                                               
        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 entry in freq)
        {
            if (entry.Key > max1)
            {
                max1 = entry.Value;
                num = entry.Key;
            }
        }
     
        // Update the number of operations
        foreach(KeyValuePair 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


输出:
2

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live