📌  相关文章
📜  需要从任一端减去最小数组元素以将K减小为0

📅  最后修改于: 2021-05-17 05:42:33             🧑  作者: Mango

给定由N个整数和整数K组成的数组arr [] ,任务是通过从数组的任一端删除数组元素并将其从K中减去来将K减小为0 。如果不可能将K减小为0 ,则打印“ -1” 。否则,请打印所需最少数量的此类操作。

例子:

方法:可以根据以下观察结果解决给定问题:

  • 考虑到需要分别从给定数组的前面和后面删除XY元素,以将K减小为0
  • 因此,其余数组元素的总和必须等于(数组元素的总和– K)

因此,从上面的观察中,我们的想法是找到总和等于(数组元素之和– K)的子数组的最大长度(例如L ) 。因此,将(N – L)的值打印为要删除的最小元素,以将K减小为0 。如果不存在任何此类子数组,则打印“ -1”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the length of
// longest subarray having sum K
int longestSubarray(int arr[],
                    int N, int K)
{
    // Stores the index of
    // the prefix sum
    unordered_map um;
 
    int sum = 0, maxLen = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Update sum
        sum += arr[i];
 
        // If the subarray starts
        // from index 0
        if (sum == K)
            maxLen = i + 1;
 
        // Add the current prefix sum
        // with index if it is not
        // present in the map um
        if (um.find(sum) == um.end())
            um[sum] = i;
 
        // Check if sum - K is
        // present in Map um or not
        if (um.find(sum - K) != um.end()) {
 
            // Update the maxLength
            if (maxLen < (i - um[sum - K]))
                maxLen = i - um[sum - K];
        }
    }
 
    // Return the required maximum length
    return maxLen;
}
 
// Function to find the minimum removal of
// array elements required to reduce K to 0
void minRequiredOperation(int arr[],
                          int N, int K)
{
    // Stores the sum of the array
    int TotalSum = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
 
        // Update sum of the array
        TotalSum += arr[i];
 
    // Find maxLen
    int maxLen = longestSubarray(
        arr, N, TotalSum - K);
 
    // If the subarray with
    // sum doesn't exist
    if (maxLen == -1) {
        cout << -1;
    }
 
    // Otherwise, print the
    // required maxmimum length
    else
        cout << N - maxLen;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 1, 1, 2 };
    int K = 4;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    minRequiredOperation(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the length of
// longest subarray having sum K
static int longestSubarray(int[] arr, int N, int K)
{
     
    // Stores the index of
    // the prefix sum
    HashMap um = new HashMap();
 
    int sum = 0, maxLen = 0;
 
    // Traverse the given array
    for(int i = 0; i < N; i++)
    {
         
        // Update sum
        sum += arr[i];
 
        // If the subarray starts
        // from index 0
        if (sum == K)
            maxLen = i + 1;
 
        // Add the current prefix sum
        // with index if it is not
        // present in the map um
        if (!um.containsKey(sum))
            um.put(sum, i);
 
        // Check if sum - K is
        // present in Map um or not
        if (um.containsKey(sum - K))
        {
             
            // Update the maxLength
            if (maxLen < (i - um.get(sum - K)))
                maxLen = i - um.get(sum - K);
        }
    }
 
    // Return the required maximum length
    return maxLen;
}
 
// Function to find the minimum removal of
// array elements required to reduce K to 0
static void minRequiredOperation(int[] arr, int N,
                                 int K)
{
     
    // Stores the sum of the array
    int TotalSum = 0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
 
        // Update sum of the array
        TotalSum += arr[i];
 
    // Find maxLen
    int maxLen = longestSubarray(arr, N, TotalSum - K);
 
    // If the subarray with
    // sum doesn't exist
    if (maxLen == -1)
    {
        System.out.println(-1);
    }
 
    // Otherwise, print the
    // required maxmimum length
    else
        System.out.println(N - maxLen);
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 3, 1, 1, 2 };
    int K = 4;
    int N = arr.length;
     
    minRequiredOperation(arr, N, K);
}
}
 
// This code is contributed by ukasp


Python3
# Python3 program for the above approach
 
# Function to find the length of
# longest subarray having sum K
def longestSubarray(arr, N, K):
   
  # Stores the index of
    # the prefix sum
    um = {}
    sum , maxLen = 0, 0
 
    # Traverse the given array
    for i in range(N):
 
        # Update sum
        sum += arr[i]
 
        # If the subarray starts
        # from index 0
        if (sum == K):
            maxLen = i + 1
 
        # Add the current prefix sum
        # with index if it is not
        # present in the map um
        if (sum not in um):
            um[sum] = i
 
        # Check if sum - K is
        # present in Map um or not
        if ((sum - K) in um):
 
            # Update the maxLength
            if (maxLen < (i - um[sum - K])):
                maxLen = i - um[sum - K]
 
    # Return the required maximum length
    return maxLen
 
# Function to find the minimum removal of
# array elements required to reduce K to 0
def minRequiredOperation(arr, N, K):
     
    # Stores the sum of the array
    TotalSum = 0
 
    # Traverse the array arr[]
    for i in range(N):
       
      # Update sum of the array
        TotalSum += arr[i]
 
    # Find maxLen
    maxLen = longestSubarray(arr, N, TotalSum - K)
 
    # If the subarray with
    # sum doesn't exist
    if (maxLen == -1):
        print (-1,end="")
 
    # Otherwise, prthe
    # required maxmimum length
    else:
        print (N - maxLen,end="")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 3, 1, 1, 2]
    K = 4
    N = len(arr)
 
    minRequiredOperation(arr, N, K)
 
    # this code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to find the length of
  // longest subarray having sum K
  static int longestSubarray(int []arr,
                             int N, int K)
  {
    // Stores the index of
    // the prefix sum
    Dictionary um = new Dictionary();
 
    int sum = 0, maxLen = 0;
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
      // Update sum
      sum += arr[i];
 
      // If the subarray starts
      // from index 0
      if (sum == K)
        maxLen = i + 1;
 
      // Add the current prefix sum
      // with index if it is not
      // present in the map um
      if (!um.ContainsKey(sum))
        um[sum] = i;
 
      // Check if sum - K is
      // present in Map um or not
      if (um.ContainsKey(sum - K)) {
 
        // Update the maxLength
        if (maxLen < (i - um[sum - K]))
          maxLen = i - um[sum - K];
      }
    }
 
    // Return the required maximum length
    return maxLen;
  }
 
  // Function to find the minimum removal of
  // array elements required to reduce K to 0
  static void minRequiredOperation(int []arr,
                                   int N, int K)
  {
 
    // Stores the sum of the array
    int TotalSum = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++)
 
      // Update sum of the array
      TotalSum += arr[i];
 
    // Find maxLen
    int maxLen = longestSubarray(
      arr, N, TotalSum - K);
 
    // If the subarray with
    // sum doesn't exist
    if (maxLen == -1) {
      Console.WriteLine(-1);
    }
 
    // Otherwise, print the
    // required maxmimum length
    else
      Console.WriteLine(N - maxLen);
  }
 
  // Driver Code
  public static void Main()
  {
    int []arr = { 1, 3, 1, 1, 2 };
    int K = 4;
    int N = arr.Length;
    minRequiredOperation(arr, N, K);
  }
}
 
// This code is contributed by SUREDRA_GANGWAR.


输出:
2

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