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

📅  最后修改于: 2021-10-28 01:38:40             🧑  作者: 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, print the
    # 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.


Javascript


输出:
2

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

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