📌  相关文章
📜  计数递减到使所有数组元素相等所需的最近的较小元素

📅  最后修改于: 2021-10-27 07:27:21             🧑  作者: Mango

给定一个由N 个非负整数组成的数组arr[] ,任务是找到使所有数组元素相等所需的操作次数。在每个操作中,任何数组元素都可以更改为其最近的较小数组元素。

例子:

方法:想法是使用排序算法和Map数据结构。请按照以下步骤解决问题:

  1. 初始化 Map 以存储每个数组元素的频率,除了最小元素,其中键 (K)是唯一元素的集合,值 (V)是它们的频率。
  2. 根据键以降序对 Map 进行排序。
  3. 0初始化两个变量ansprev_val分别存储当前答案和前缀和。
  4. 现在迭代 Map 并将每个元素的相应频率与prev_val一起添加ans作为ans = ans + (freq) + prev_val
  5. 在迭代 Map 时,每次都将prev_val增加当前元素的频率。
  6. 完全遍历Map后,将ans打印为最小操作次数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print the minimum number of
// decrements to make all elements equals
int MinimumNoOfOperations(int arr[], int n)
{
 
    // Find minimum element
    int min_ele = INT_MAX;
    for (int i = 0; i < n; ++i) {
        min_ele = min(min_ele, arr[i]);
    }
 
    // Stores frequencies of array elements
    map > mp;
 
    // Update frequencies in the Map
    for (int i = 0; i < n; ++i) {
 
        if (arr[i] == min_ele)
            continue;
        else
            mp[arr[i]]++;
    }
 
    // Iterate the map
    map::iterator it;
 
    // Stores the count of
    // decrements at each iteration
    int prev_val = 0;
 
    // Stores the total
    // count of decrements
    int ans = 0;
 
    // Calculate the number of decrements
    for (it = mp.begin(); it != mp.end();
         ++it) {
 
        ans += (it->second + prev_val);
        prev_val += it->second;
    }
 
    // Return minimum operations
    return ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 5, 4, 3, 5, 4 };
 
    // Given size
    int size = sizeof(arr)
               / sizeof(arr[0]);
 
    // Function call
    cout << MinimumNoOfOperations(
        arr, size);
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
 
class solution{
    
// Function to print the minimum
// number of decrements to make
// all elements equals
static int MinimumNoOfOperations(int arr[],
                                 int n)
{
  // Find minimum element
  int min_ele = Integer.MAX_VALUE;
   
  for (int i = 0; i < n; ++i)
  {
    min_ele = Math.min(min_ele,
                       arr[i]);
  }
 
  // Stores frequencies of array
  // elements
  TreeMap mp =
          new TreeMap(
          Collections.reverseOrder());
 
  // Update frequencies in
  // the Map
  for (int i = 0; i < n; ++i)
  {
    if (arr[i] == min_ele)
      continue;
    else
      mp.put(arr[i],
      mp.getOrDefault(arr[i], 0) + 1);
  }
 
  // Stores the count of
  // decrements at each
  // iteration
  int prev_val = 0;
 
  // Stores the total
  // count of decrements
  int ans = 0;
 
  // Calculate the number of
  // decrements
  for (Map.Entry it : mp.entrySet())
  {
    ans += (it.getValue() + prev_val);
    prev_val += it.getValue();
  }
 
  // Return minimum operations
  return ans;
}
 
// Driver Code
public static void main(String args[])
{
  // Given array
  int arr[] = {2, 5, 4, 3, 5, 4};
   
  // Given size
  int size = arr.length;
   
  // Function call
  System.out.println(
  MinimumNoOfOperations(arr, size));
}
}
 
// This code is contributed by bgangwar59


Python3
# Python3 program for the above approach
import sys
 
# Function to print the minimum number of
# decrements to make all elements equals
def MinimumNoOfOperations(arr, n):
     
    # Find minimum element
    min_ele = sys.maxsize
     
    for i in range(n):
        min_ele = min(min_ele, arr[i])
 
    # Stores frequencies of array elements
    mp = {}
 
    # Update frequencies in the Map
    for i in range(n):
        if (arr[i] == min_ele):
            continue
        else:
            mp[arr[i]] = mp.get(arr[i], 0) + 1
             
    # Stores the count of
    # decrements at each iteration
    prev_val = 0
 
    # Stores the total
    # count of decrements
    ans = 0
 
    # Calculate the number of decrements
    for it in mp:
        ans += (mp[it] + prev_val)
        prev_val += mp[it]
 
    # Return minimum operations
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 2, 5, 4, 3, 5, 4 ]
 
    # Given size
    size = len(arr)
 
    # Function call
    print(MinimumNoOfOperations(arr, size))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System.Collections.Generic;
using System;
using System.Linq;
 
class GFG{
    
// Function to print the minimum
// number of decrements to make
// all elements equals
static int MinimumNoOfOperations(int []arr,
                                 int n)
{
   
  // Find minimum element
  int min_ele = 1000000000;
   
  for(int i = 0; i < n; ++i)
  {
      min_ele = Math.Min(min_ele, arr[i]);
  }
 
  // Stores frequencies of array
  // elements
  Dictionary mp = new Dictionary();
 
  // Update frequencies in
  // the Map
  for(int i = 0; i < n; ++i)
  {
    if (arr[i] == min_ele)
      continue;
    else
    {
      if (mp.ContainsKey(arr[i]) == true)
        mp[arr[i]] += 1;
      else
        mp[arr[i]] = 1;   
    }
  }
 
  // Stores the count of
  // decrements at each
  // iteration
  int prev_val = 0;
 
  // Stores the total
  // count of decrements
  int ans = 0;
 
  // Calculate the number of
  // decrements
  var val = mp.Keys.ToList();
  foreach(var key in val)
  {
    ans += (mp[key] + prev_val);
    prev_val += mp[key];
  }
   
  // Return minimum operations
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
   
  // Given array
  int []arr = { 2, 5, 4, 3, 5, 4 };
   
  // Given size
  int size = arr.Length;
   
  // Function call
  Console.WriteLine(MinimumNoOfOperations(
    arr, size));
}
}
 
// This code is contributed by Stream_Cipher


Javascript


输出:
11

时间复杂度: O(N),其中 N 是数组的大小。
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程