Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0

Given an array nums[] and an integer X, the task is to reduce X to 0 by removing either the leftmost or the rightmost array elements and subtracting its value from X, minimum number of times. If it’s possible to reduce X to 0, print the count of operations required. Otherwise, return -1.
Examples:
Input: nums[] = {3,2,20,1,1,3}, X = 10
Output: 5
Explanation: X (= 10) – 3 – 1 – 1 – 3 – 2 = 0. Therefore, the number of operations required is 5.ÂInput: nums[] = {1, 1, 4, 2, 3}, X = 5
Output: 2
Explanation: X (= 5) – 3 – 2 = 0. Therefore, the number of operations required is 2.Â
Approach: The given problem can be solved using Two Pointers technique. Follow the steps below to solve the problem.Â
- Maintain two pointers left and right, pointing to the ends of the left and right subarrays excluded from X.
- Initialize left to consider the entire array, and right to include nothing.
- Therefore, reduce X by the sum of the array.
- Now, iterate until left reaches the front of the array.
- If the sum of the left and the right subarrays exceeds X (i.e. X < 0), shift left by an index to the left and increase X that element.
- If the sum of the left and the right subarrays is less than X (i.e. X > 0), shift right pointer by an index to the left and reduce X by that element.
- If X is found to be 0 at any point, update the minimum number of operations required.
- Print the minimum number of operations required.
- Below is the implementation of the above approach:
C++14
// C++ program to implement // the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to count the minimum// number of operations required// to reduce x to 0static int minOperations(int nums[], int N,                         int x){         // If sum of the array    // is less than x    int sum = 0;         for(int i = 0; i < x; i++)        sum += nums[i];             if (sum < x)        return -1;         // Stores the count    // of operations    int ans = INT_MAX;         // Two pointers to traverse the array    int l = N - 1, r = N;         // Reduce x by the sum    // of the entire array    x -= sum;         // Iterate until l reaches    // the front of the array    while (l >= 0)    {             // If sum of elements from        // the front exceeds x        if (x <= 0)         {                     // Shift towards left            x += nums[l];            l -= 1;        }                 // If sum exceeds 0        if (x > 0)        {                     // Reduce x by elements            // from the right            r -= 1;            x -= nums[r];        }                 // If x is reduced to 0        if (x == 0)        {                     // Update the minimum count            // of operations required            ans = min(ans,            (l + 1) + (N - r));        }    }         if (ans < INT_MAX)        return ans;    else        return -1;}Â
// Driver Codeint main(){    int nums[] = { 1, 1, 4, 2, 3 };          // Size of the array    int N = sizeof(nums) / sizeof(nums[0]);         int x = 5;    cout << minOperations(nums, N, x);Â
    return 0;}Â
// This code is contributed by code_hunt |
Java
// Java program to implement // the above approach import java.util.*;Â
class GFG{Â
  // Function to count the minimum  // number of operations required  // to reduce x to 0  static int minOperations(int nums[], int x)  {Â
    // If sum of the array    // is less than x    int sum = 0;    for (int i = 0; i < x; i++)      sum += nums[i];    if (sum < x)      return -1;Â
    // Stores the count    // of operations    int ans = Integer.MAX_VALUE;Â
    // Two pointers to traverse the array    int l = nums.length - 1, r = nums.length;Â
    // Reduce x by the sum    // of the entire array    x -= sum;Â
    // Iterate until l reaches    // the front of the array    while (l >= 0) {Â
      // If sum of elements from      // the front exceeds x      if (x <= 0) {Â
        // Shift towards left        x += nums[l];        l -= 1;      }Â
      // If sum exceeds 0      if (x > 0) {Â
        // Reduce x by elements        // from the right        r -= 1;        x -= nums[r];      }Â
      // If x is reduced to 0      if (x == 0) {Â
        // Update the minimum count        // of operations required        ans = Math.min(ans,                       (l + 1) + (nums.length - r));      }    }    if (ans < Integer.MAX_VALUE)      return ans;    else      return -1;  }Â
  // Driver Code  public static void main(String[] args)   {    int[] nums = { 1, 1, 4, 2, 3 };    int x = 5;    System.out.println(minOperations(nums, x));  }}Â
// This code is contributed by shubhamsingh10 |
Python3
# Python3 Program to implement# the above approachÂ
import mathÂ
# Function to count the minimum# number of operations required# to reduce x to 0def minOperations(nums, x):Â
    # If sum of the array    # is less than x    if sum(nums) < x:        return -1Â
    # Stores the count    # of operations    ans = math.infÂ
    # Two pointers to traverse the array    l, r = len(nums)-1, len(nums)Â
    # Reduce x by the sum    # of the entire array    x -= sum(nums)Â
    # Iterate until l reaches    # the front of the array    while l >= 0:Â
        # If sum of elements from        # the front exceeds x        if x <= 0:Â
            # Shift towards left            x += nums[l]            l -= 1Â
        # If sum exceeds 0        if x > 0:Â
            # Reduce x by elements            # from the right            r -= 1            x -= nums[r]Â
        # If x is reduced to 0        if x == 0:Â
            # Update the minimum count            # of operations required            ans = min(ans, (l+1) + (len(nums)-r))Â
    return ans if ans < math.inf else -1Â
Â
# Driver Codenums = [1, 1, 4, 2, 3]x = 5print(minOperations(nums, x)) |
C#
// C# Program to implement// the above approachusing System;class GFG {Â
  // Function to count the minimum  // number of operations required  // to reduce x to 0  static int minOperations(int[] nums, int x)  {Â
    // If sum of the array    // is less than x    int sum = 0;    for (int i = 0; i < x; i++)      sum += nums[i];    if (sum < x)      return -1;Â
    // Stores the count    // of operations    int ans = Int32.MaxValue;Â
    // Two pointers to traverse the array    int l = nums.Length - 1, r = nums.Length;Â
    // Reduce x by the sum    // of the entire array    x -= sum;Â
    // Iterate until l reaches    // the front of the array    while (l >= 0) {Â
      // If sum of elements from      // the front exceeds x      if (x <= 0) {Â
        // Shift towards left        x += nums[l];        l -= 1;      }Â
      // If sum exceeds 0      if (x > 0) {Â
        // Reduce x by elements        // from the right        r -= 1;        x -= nums[r];      }Â
      // If x is reduced to 0      if (x == 0) {Â
        // Update the minimum count        // of operations required        ans = Math.Min(ans,                       (l + 1) + (nums.Length - r));      }    }    if (ans < Int32.MaxValue)      return ans;    else      return -1;  }Â
  // Driver Code  public static void Main()  {    int[] nums = { 1, 1, 4, 2, 3 };    int x = 5;    Console.Write(minOperations(nums, x));  }}Â
// This code is contributed by ukasp. |
Javascript
<script>Â
// Javascript program to implement // the above approachÂ
// Function to count the minimum// number of operations required// to reduce x to 0function minOperations(nums, x){         // If sum of the array    // is less than x    let sum = 0;    for(let i = 0; i < x; i++)        sum += nums[i];             if (sum < x)        return -1;         // Stores the count    // of operations    let ans = Number.MAX_VALUE;         // Two pointers to traverse the array    let l = nums.length - 1, r = nums.length;         // Reduce x by the sum    // of the entire array    x -= sum;         // Iterate until l reaches    // the front of the array    while (l >= 0)     {             // If sum of elements from        // the front exceeds x        if (x <= 0)         {                         // Shift towards left            x += nums[l];            l -= 1;        }                 // If sum exceeds 0        if (x > 0)         {                     // Reduce x by elements            // from the right            r -= 1;            x -= nums[r];        }                 // If x is reduced to 0        if (x == 0)         {                     // Update the minimum count            // of operations required            ans = Math.min(ans,                          (l + 1) +                           (nums.length - r));        }    }         if (ans < Number.MAX_VALUE)        return ans;    else        return -1;}Â
// Driver codelet nums = [ 1, 1, 4, 2, 3 ];let x = 5;Â
document.write(minOperations(nums, x));Â
// This code is contributed by target_2Â Â Â Â Â </script> |
PHP
// PHP program to implement<?phpÂ
// Function to count the minimum numberfunction minOperations($nums, $N, $x) {Â
    // sum of the array    $sum = 0;Â
    for($i = 0; $i < $x; $i++)        $sum += $nums[$i];Â
    if ($sum < $x)        return -1;Â
    // Stores the count of operations    $ans = PHP_INT_MAX;Â
    // Two pointers to traverse the array    $l = $N - 1;    $r = $N;Â
    // Reduce x by the sum    $x -= $sum;Â
    // Iterate until l reaches    while ($l >= 0)    {Â
        // sum of elements from        if ($x <= 0)        {Â
            // Shift towards left            $x += $nums[$l];            $l -= 1;        }Â
        // If sum exceeds 0        if ($x > 0)        {            $r -= 1;            $x -= $nums[$r];        }Â
        // x is reduced to 0        if ($x == 0)        {Â
            // updating the minimum count            $ans = min($ans, ($l + 1) + ($N - $r));        }    }Â
    if ($ans < PHP_INT_MAX)        return $ans;    else        return -1;}Â
// Driver Code    $nums = array(1, 1, 4, 2, 3);    $N = count($nums);    $x = 5;    echo minOperations($nums, $N, $x);?> |
2
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



