📌  相关文章
📜  要删除的最小子数组的大小,以使数组元素的数量大于或小于K

📅  最后修改于: 2021-04-21 21:02:29             🧑  作者: Mango

给定一个整数K和一个由N个整数组成的数组arr [] ,任务是找到要删除的最小可能长度的子数组的长度,以使其余数组中小于和大于K的数组元素的个数为平等的。

例子:

天真的方法:解决问题的最简单方法是生成所有可能的子数组,并遍历其余数组,以保留严格大于和小于整数K的数组元素的数量。然后,选择最小的子数组,其删除将给出一个数组,该数组具有相等数量的越来越大的元素。

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

高效的方法:想法是使用哈希对数组进行一些修改以在O(N)时间内解决它。给定的数组可以具有3种类型的元素:

  • element = K :将element更改为0(因为我们需要严格大于K或小于K的元素)
  • 元素> K :将元素更改为1
  • 元素 :将元素更改为-1

现在,计算所有数组元素的总和,并将其存储在一个变量中,例如total_sum 。现在,total_sum可以具有三个可能的值范围:

  • 如果total_sum = 0 :所有1都被-1s抵消。因此,已经存在相等数量的大于或小于K的元素。不需要删除操作。因此,将0打印为所需答案。
  • 如果total_sum> 0-1s不能取消一些。即阵列具有多个大于K的元素和小于K的要素数少的数目。因此,找到sum = total_sum的最小子数组,因为它是要删除的最小子数组
  • 如果total_sum <0:一些-1将被取消1s。即阵列具有多于k和大于K的要素数少较小元素的个数。因此,找到sum = total_sum的最小子数组,因为它是要删除的最小子数组

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function ot find the length
// of the smallest subarray
int smallSubarray(int arr[], int n,
                  int total_sum)
{
    // Stores (prefix Sum, index)
    // as (key, value) mappings
    unordered_map m;
    int length = INT_MAX;
    int prefixSum = 0;
 
    // Iterate till N
    for (int i = 0; i < n; i++) {
 
        // Update the prefixSum
        prefixSum += arr[i];
 
        // Update the length
        if (prefixSum == total_sum) {
            length = min(length, i + 1);
        }
 
        // Put the latest index to
        // find the minimum length
        m[prefixSum] = i;
 
        if (m.count(prefixSum - total_sum)) {
 
            // Update the length
            length
                = min(length,
                      i - m[prefixSum - total_sum]);
        }
    }
 
    // Return the answer
    return length;
}
 
// Function to find the length of
// the largest subarray
int smallestSubarrayremoved(int arr[], int n,
                            int k)
{
 
    // Stores the sum of all array
    // elements after modification
    int total_sum = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Change greater than k to 1
        if (arr[i] > k) {
            arr[i] = 1;
        }
 
        // Change smaller than k to -1
        else if (arr[i] < k) {
            arr[i] = -1;
        }
 
        // Change equal to k to 0
        else {
            arr[i] = 0;
        }
 
        // Update total_sum
        total_sum += arr[i];
    }
 
    // No deletion required, return 0
    if (total_sum == 0) {
        return 0;
    }
 
    else {
 
        // Delete smallest subarray
        // that has sum = total_sum
        return smallSubarray(arr, n,
                             total_sum);
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 12, 16, 12, 13, 10 };
    int K = 13;
 
    int n = sizeof(arr) / sizeof(int);
 
    cout << smallestSubarrayremoved(
        arr, n, K);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function ot find the length
// of the smallest subarray
static int smallSubarray(int arr[], int n,
                         int total_sum)
{
     
    // Stores (prefix Sum, index)
    // as (key, value) mappings
    Map m = new HashMap();
                                  
    int length = Integer.MAX_VALUE;
    int prefixSum = 0;
     
    // Iterate till N
    for(int i = 0; i < n; i++)
    {
         
        // Update the prefixSum
        prefixSum += arr[i];
         
        // Update the length
        if (prefixSum == total_sum)
        {
            length = Math.min(length, i + 1);
        }
         
        // Put the latest index to
        // find the minimum length
        m.put(prefixSum, i);
         
        if (m.containsKey(prefixSum - total_sum))
        {
             
            // Update the length
            length = Math.min(length,
                              i - m.get(prefixSum -
                                        total_sum));
        }
    }
     
    // Return the answer
    return length;
}
 
// Function to find the length of
// the largest subarray
static int smallestSubarrayremoved(int arr[], int n,
                                   int k)
{
     
    // Stores the sum of all array
    // elements after modification
    int total_sum = 0;
     
    for(int i = 0; i < n; i++)
    {
         
        // Change greater than k to 1
        if (arr[i] > k)
        {
            arr[i] = 1;
        }
         
        // Change smaller than k to -1
        else if (arr[i] < k)
        {
            arr[i] = -1;
        }
         
        // Change equal to k to 0
        else
        {
            arr[i] = 0;
        }
         
        // Update total_sum
        total_sum += arr[i];
    }
     
    // No deletion required, return 0
    if (total_sum == 0)
    {
        return 0;
    }
    else
    {
         
        // Delete smallest subarray
        // that has sum = total_sum
        return smallSubarray(arr, n, total_sum);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 12, 16, 12, 13, 10 };
    int K = 13;
    int n = arr.length;
     
    System.out.println(
        smallestSubarrayremoved(arr, n, K));
}
}
 
// This code is contributed by chitranayal


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function ot find the length
# of the smallest subarray
def smallSubarray(arr, n, total_sum):
 
    # Stores (prefix Sum, index)
    # as (key, value) mappings
    m = {}
    length = sys.maxsize
    prefixSum = 0
 
    # Iterate till N
    for i in range(n):
 
        # Update the prefixSum
        prefixSum += arr[i]
 
        # Update the length
        if(prefixSum == total_sum):
            length = min(length, i + 1)
 
        # Put the latest index to
        # find the minimum length
        m[prefixSum] = i
 
        if((prefixSum - total_sum) in m.keys()):
 
            # Update the length
            length = min(length,
                         i - m[prefixSum - total_sum])
 
    # Return the answer
    return length
 
# Function to find the length of
# the largest subarray
def smallestSubarrayremoved(arr, n, k):
 
    # Stores the sum of all array
    # elements after modification
    total_sum = 0
 
    for i in range(n):
 
        # Change greater than k to 1
        if(arr[i] > k):
            arr[i] = 1
 
        # Change smaller than k to -1
        elif(arr[i] < k):
            arr[i] = -1
 
        # Change equal to k to 0
        else:
            arr[i] = 0
 
        # Update total_sum
        total_sum += arr[i]
 
    # No deletion required, return 0
    if(total_sum == 0):
        return 0
    else:
         
        # Delete smallest subarray
        # that has sum = total_sum
        return smallSubarray(arr, n,
                             total_sum)
                              
# Driver Code
arr = [ 12, 16, 12, 13, 10 ]
K = 13
 
n = len(arr)
 
# Function call
print(smallestSubarrayremoved(arr, n, K))
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Function ot find the length
// of the smallest subarray
static int smallSubarray(int []arr, int n,
                         int total_sum)
{
     
    // Stores (prefix Sum, index)
    // as (key, value) mappings
    Dictionary m = new Dictionary();
                                  
    int length = int.MaxValue;
    int prefixSum = 0;
     
    // Iterate till N
    for(int i = 0; i < n; i++)
    {
         
        // Update the prefixSum
        prefixSum += arr[i];
         
        // Update the length
        if (prefixSum == total_sum)
        {
            length = Math.Min(length, i + 1);
        }
         
        // Put the latest index to
        // find the minimum length
        if (m.ContainsKey(prefixSum))
            m[prefixSum] = i;
        else
            m.Add(prefixSum, i);
         
        if (m.ContainsKey(prefixSum - total_sum))
        {
             
            // Update the length
            length = Math.Min(length,
                              i - m[prefixSum -
                                    total_sum]);
        }
    }
     
    // Return the answer
    return length;
}
 
// Function to find the length of
// the largest subarray
static int smallestSubarrayremoved(int []arr,
                                   int n, int k)
{
     
    // Stores the sum of all array
    // elements after modification
    int total_sum = 0;
     
    for(int i = 0; i < n; i++)
    {
         
        // Change greater than k to 1
        if (arr[i] > k)
        {
            arr[i] = 1;
        }
         
        // Change smaller than k to -1
        else if (arr[i] < k)
        {
            arr[i] = -1;
        }
         
        // Change equal to k to 0
        else
        {
            arr[i] = 0;
        }
         
        // Update total_sum
        total_sum += arr[i];
    }
     
    // No deletion required, return 0
    if (total_sum == 0)
    {
        return 0;
    }
    else
    {
         
        // Delete smallest subarray
        // that has sum = total_sum
        return smallSubarray(arr, n, total_sum);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 12, 16, 12, 13, 10 };
    int K = 13;
    int n = arr.Length;
     
    Console.WriteLine(
            smallestSubarrayremoved(arr, n, K));
}
}
 
// This code is contributed by Rajput-Ji


输出:
3



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