📌  相关文章
📜  从给定数组中精确删除K后,可能会出现最大反转

📅  最后修改于: 2021-05-17 19:22:16             🧑  作者: Mango

给定一个由N个整数和一个整数K组成的数组arr [] ,任务是找到在除去K个数组元素后可能的给定数组的最大反转数。

例子:

方法:请按照以下步骤解决问题:

  • 从数组arr []中删除K个元素后,初始化变量res来存储最大数量的反转。
  • 初始化长度为N的二进制字符串S ,以存储要从数组arr []中考虑的(N-K)个元素。
  • 0存储在[0,K – 1]位置,表示K个已删除元素,将1存储在[K,N – 1]位置,表示(N – K)个字符串S中的所选元素。
  • 生成字符串S的所有排列并执行以下操作:
    • 初始化数组v ,以根据字符串S存储从arr []中选择的(N-K)个元素。
    • 计算数组v中的求反数并将其存储在cnt中
    • res更新为rescnt的最大值。
  • 完成上述步骤后,打印res值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the maximum number
// of inversions after K removals
void maximizeInversions(int a[], int n,
                        int k)
{
    // Initialize a binary string
    string s;
 
    // Interate over range [0, K]
    for (int i = 0; i < k; i++)
    {
 
        // Append 0 to the string
        s += "0";
    }
 
    for (int i = k; i < n; i++)
    {
 
        // Append 1 to the string
        s += "1";
    }
 
    // Stores the maximum number of
    // inversions after K removals
    int res = 0;
 
    // Generate all permutations
    // of string s
    do
    {
 
        // Stores the current array
        vector v;
 
        // Stores number of inversions
        // of the current array
        int cnt = 0;
 
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '1')
                v.push_back(a[i]);
        }
 
        // Find the number of inversions
        // in the array v
        for (int i = 0;
             i < v.size() - 1; i++)
        {
 
            for (int j = i + 1;
                 j < v.size(); j++)
            {
 
                // Condition to check if the
                // number of pairs satisfy
                // required condition
                if (v[i] >= v[j])
 
                    // Increment the count
                    cnt++;
            }
        }
 
        // Update res
        res = max(res, cnt);
 
    }
  while (next_permutation(s.begin(),
                              s.end()));
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    // Function Call
    maximizeInversions(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to find the maximum number
// of inversions after K removals
static void maximizeInversions(int a[], int n,
                                int k)
{
    // Initialize a binary String
    String s="";
 
    // Interate over range [0, K]
    for (int i = 0; i < k; i++)
    {
 
        // Append 0 to the String
        s += "0";
    }
 
    for (int i = k; i < n; i++)
    {
 
        // Append 1 to the String
        s += "1";
    }
 
    // Stores the maximum number of
    // inversions after K removals
    int res = 0;
 
    // Generate all permutations
    // of String s
    do
    {
 
        // Stores the current array
        Vector v = new Vector<>();
 
        // Stores number of inversions
        // of the current array
        int cnt = 0;
 
        for (int i = 0; i < n; i++)
        {
            if (s.charAt(i) == '1')
                v.add(a[i]);
        }
 
        // Find the number of inversions
        // in the array v
        for (int i = 0;
             i < v.size() - 1; i++)
        {
 
            for (int j = i + 1;
                 j < v.size(); j++)
            {
 
                // Condition to check if the
                // number of pairs satisfy
                // required condition
                if (v.get(i) >= v.get(j))
 
                    // Increment the count
                    cnt++;
            }
        }
 
        // Update res
        res = Math.max(res, cnt);
 
    }
  while (next_permutation(s));
 
    // Print the result
    System.out.print(res);
}
 
static boolean next_permutation(String str)
{
    char []p = str.toCharArray();
      for (int a = p.length - 2; a >= 0; --a)
        if (p[a] < p[a + 1])
          for (int b = p.length - 1;; --b)
            if (p[b] > p[a])
            {
              char t = p[a];
              p[a] = p[b];
              p[b] = t;
              for (++a, b = p.length - 1;
                   a < b; ++a, --b)
              {
                t = p[a];
                p[a] = p[b];
                p[b] = t;
              }
              return false;
            }
      return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 4, 1 };
    int N = arr.length;
    int K = 2;
 
    // Function Call
    maximizeInversions(arr, N, K);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
def next_permutation(Str):
     
    p = list(Str)
     
    for a in range(len(p) - 2, -1, -1):
        if p[a] < p[a + 1]:
            b = len(p) - 1
             
            while True:
                if p[b] > p[a]:
                    t = p[a]
                    p[a] = p[b]
                    p[b] = t
                    a += 1
                    b = len(p) - 1
                     
                    while a < b:
                        t = p[a]
                        p[a] = p[b]
                        p[b] = t
                        a += 1
                        b -= 1
                         
                    return False
                     
                b -= 1
                 
    return True
 
# Function to find the maximum number
# of inversions after K removals
def maximizeInversions(a, n, k):
     
    # Initialize a binary string
    s = ""
 
    # Interate over range [0, K]
    for i in range(k):
         
        # Append 0 to the string
        s += "0"
 
    for i in range(k, n):
         
        # Append 1 to the string
        s += "1"
 
    # Stores the maximum number of
    # inversions after K removals
    res = 0
 
    # Generate all permutations
    # of string s
    while (True):
         
        # Stores the current array
        v = []
 
        # Stores number of inversions
        # of the current array
        cnt = 0
 
        for i in range(n):
            if (s[i] == '1'):
                v.append(a[i])
                 
        # Find the number of inversions
        # in the array v
        for i in range(len(v) - 1):
            for j in range(i + 1, len(v)):
                 
                # Condition to check if the
                # number of pairs satisfy
                # required condition
                if (v[i] >= v[j]):
 
                    # Increment the count
                    cnt += 1
 
        # Update res
        res = max(res, cnt)
         
        if (not next_permutation(s)):
            break
 
    # Print the result
    print(res)
 
# Driver Code
arr = [ 2, 3, 4, 1 ]
N = len(arr)
K = 2
 
# Function Call
maximizeInversions(arr, N, K)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to find the maximum number
// of inversions after K removals
static void maximizeInversions(int []a, int n,
                                int k)
{
    // Initialize a binary String
    String s="";
 
    // Interate over range [0, K]
    for (int i = 0; i < k; i++)
    {
 
        // Append 0 to the String
        s += "0";
    }
 
    for (int i = k; i < n; i++)
    {
 
        // Append 1 to the String
        s += "1";
    }
 
    // Stores the maximum number of
    // inversions after K removals
    int res = 0;
 
    // Generate all permutations
    // of String s
    do
    {
 
        // Stores the current array
        List v = new List();
 
        // Stores number of inversions
        // of the current array
        int cnt = 0;
 
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '1')
                v.Add(a[i]);
        }
 
        // Find the number of inversions
        // in the array v
        for (int i = 0;
             i < v.Count - 1; i++)
        {
 
            for (int j = i + 1;
                 j < v.Count; j++)
            {
 
                // Condition to check if the
                // number of pairs satisfy
                // required condition
                if (v[i] >= v[j])
 
                    // Increment the count
                    cnt++;
            }
        }
 
        // Update res
        res = Math.Max(res, cnt);
 
    }
  while (next_permutation(s));
 
    // Print the result
    Console.Write(res);
}
 
static bool next_permutation(String str)
{
    char []p = str.ToCharArray();
      for (int a = p.Length - 2; a >= 0; --a)
        if (p[a] < p[a + 1])
          for (int b = p.Length - 1;; --b)
            if (p[b] > p[a])
            {
              char t = p[a];
              p[a] = p[b];
              p[b] = t;
              for (++a, b = p.Length - 1;
                   a < b; ++a, --b)
              {
                t = p[a];
                p[a] = p[b];
                p[b] = t;
              }
              return false;
            }
      return true;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 2, 3, 4, 1 };
    int N = arr.Length;
    int K = 2;
 
    // Function Call
    maximizeInversions(arr, N, K);
}
}
 
// This code contributed by Princi Singh


输出:
1

时间复杂度: O((N!)*(N – K) 2 )
辅助空间: O(N)