Open In App

Check if the Array elements can be made 0 with given conditions

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays arr[] and arr2[], and a value K, the task is to check whether the array arr[] can be made to all zeros such that in each operation all elements less than K are made to 0 else they are subtracted by K then the K gets decayed by the smallest value of the array arr2[] whose arr[i] is not zero.

Examples: 

Input: arr[] = {18, 5, 13, 9, 10, 1}, arr2[] = {2, 7, 2, 1, 2, 6}, K = 7
Output: YES
Explanation: In the 1st operation : arr[] = {11, 0, 6, 2, 3, 0}, K = 7 – min(2, 7, 2, 1, 2, 6) = 6
In the 2nd operation: arr[] = {5, 0, 0, 0, 0, 0}, K = 6 – 2 = 4
In the 3rd operation: arr[]  = {1, 0, 0, 0, 0, 0} K = 4 – 2 = 2
In the 4th operation: arr[] = {0, 0, 0, 0, 0} all are made to 0 so answer is YES.

Input: arr[] = {5, 5, 5}, arr2[] = {4, 4, 4}, K = 4
Output: NO 
Explanation: In the 1st operation: arr[] = {1, 1, 1, 1}, K = 0 K has already become 0 so no way to make the array elements to 0 so NO.

Approach: To solve the problem follow the below idea:

This problem can be solved greedily by maintaining a vector of pairs with {arr2[i], arr[i]} and sorting it based on the arr2[i]. After sorting we vary the values of arr[i] and K on each operation until K is not equal to 0.

Follow these steps to solve the above problem:

  • Initialize a vector of pairs v to store the arr2[i] and arr[i].
  • Sort the vector v based on the first element of the pair i.e arr2[i].
  • Initialize the value to be reduced from arr[i] as sum = K
  • Iterate while K > 0 and i < n and decay the value of K by v[i].first and apply operation while arr[i] which is v[i].second is > 0 also incrementing the sum by K
  • Initialize ctr = 0 to check whether all the array elements of arr[] are made to 0
  • If all are made to 0 print YES else print NO.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether all the array
// elements can be made to 0.
void is_possible(int arr[], int brr[], int n, int m, int k)
{
    // Initialize a vector of pairs v to
    // store the brr[i] and arr[i]
    vector<pair<int, int> > v;
 
    for (int i = 0; i < n; i++) {
        v.push_back({ brr[i], arr[i] });
    }
 
    // Sort the vector v based on the first
    // element of the pair i.e brr[i]
    sort(v.begin(), v.end());
 
    int i = 0;
 
    // Initialize the value to be reduced
    // from arr[i] as sum = k
    int sum = k;
 
    // Iterate while k > 0 and i < n
    // and decay the value of k by v[i].
    // first and apply operation while
    // arr[i] which is v[i].second is > 0
    // also incrementing the sum by k
    while (k > 0 && i < n) {
        while ((v[i].second - sum) > 0) {
 
            // Decay the value k
            k = k - v[i].first;
            if (k >= 0)
                sum += k;
            else
                break;
        }
        i++;
    }
 
    // Initialize ctr =0 to check whether
    // all the array elements of arr[]
    // are made to 0
    int ctr = 0;
    for (auto itr : v) {
        if ((itr.second - sum) <= 0) {
            ctr++;
        }
    }
 
    // If all are made to 0 print YES
    // else print NO
    if (ctr == n) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 18, 5, 13, 9, 10, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int arr2[] = { 2, 7, 2, 1, 2, 6 };
    int m = sizeof(arr2) / sizeof(arr2[0]);
    int K = 7;
    is_possible(arr, arr2, n, m, K);
 
    int brr[] = { 5, 5, 5 };
    int n2 = sizeof(brr) / sizeof(brr[0]);
    int brr2[] = { 4, 4, 4 };
    int m2 = sizeof(brr2) / sizeof(brr2[0]);
    int K2 = 4;
    is_possible(brr, brr2, n2, m2, K2);
    return 0;
}


Java




import java.util.*;
 
class Main {
    static void is_possible(int[] arr, int[] brr, int n, int m, int k) {
        // Initialize a vector of pairs v to
        // store the brr[i] and arr[i]
        List<Map.Entry<Integer, Integer>> v = new ArrayList<>();
 
        for (int i = 0; i < n; i++) {
            v.add(new AbstractMap.SimpleEntry<>(brr[i], arr[i]));
        }
 
        // Sort the vector v based on the first
        // element of the pair i.e brr[i]
        Collections.sort(v, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));
 
        int i = 0;
 
        // Initialize the value to be reduced
        // from arr[i] as sum = k
        int sum = k;
 
        // Iterate while k > 0 and i < n
        // and decay the value of k by v[i].
        // first and apply operation while
        // arr[i] which is v[i].second is > 0
        // also incrementing the sum by k
        while (k > 0 && i < n) {
            while ((v.get(i).getValue() - sum) > 0) {
 
                // Decay the value k
                k = k - v.get(i).getKey();
                if (k >= 0)
                    sum += k;
                else
                    break;
            }
            i++;
        }
 
        // Initialize ctr =0 to check whether
        // all the array elements of arr[]
        // are made to 0
        int ctr = 0;
        for (Map.Entry<Integer, Integer> itr : v) {
            if ((itr.getValue() - sum) <= 0) {
                ctr++;
            }
        }
 
        // If all are made to 0 print YES
        // else print NO
        if (ctr == n) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }
 
    public static void main(String[] args) {
        int[] arr = { 18, 5, 13, 9, 10, 1 };
        int n = arr.length;
        int[] arr2 = { 2, 7, 2, 1, 2, 6 };
        int m = arr2.length;
        int K = 7;
        is_possible(arr, arr2, n, m, K);
 
        int[] brr = { 5, 5, 5 };
        int n2 = brr.length;
        int[] brr2 = { 4, 4, 4 };
        int m2 = brr2.length;
        int K2 = 4;
        is_possible(brr, brr2, n2, m2, K2);
    }
}
//This is contributed by ishan0202


Python3




def is_possible(arr, brr, n, m, k):
    # Initialize a list of tuples v to
    # store the brr[i] and arr[i]
    v = []
    for i in range(n):
        v.append((brr[i], arr[i]))
 
    # Sort the list v based on the first
    # element of the tuple i.e brr[i]
    v.sort(key=lambda x: x[0])
 
    i = 0
    # Initialize the value to be reduced
    # from arr[i] as sum = k
    sum = k
 
    # Iterate while k > 0 and i < n
    # and decay the value of k by v[i][0]
    # and apply operation while
    # arr[i] which is v[i][1] is > 0
    # also incrementing the sum by k
    while k > 0 and i < n:
        while (v[i][1] - sum) > 0:
            # Decay the value k
            k = k - v[i][0]
            if k >= 0:
                sum += k
            else:
                break
        i += 1
 
    # Initialize ctr =0 to check whether
    # all the array elements of arr[]
    # are made to 0
    ctr = 0
    for i in range(n):
        if (v[i][1] - sum) <= 0:
            ctr += 1
 
    # If all are made to 0 print YES
    # else print NO
    if ctr == n:
        print("YES")
    else:
        print("NO")
 
 
# Driver Code
if __name__ == "__main__":
    arr = [18, 5, 13, 9, 10, 1]
    n = len(arr)
    arr2 = [2, 7, 2, 1, 2, 6]
    m = len(arr2)
    K = 7
    is_possible(arr, arr2, n, m, K)
 
    brr = [5, 5, 5]
    n2 = len(brr)
    brr2 = [4, 4, 4]
    m2 = len(brr2)
    K2 = 4
    is_possible(brr, brr2, n2, m2, K2)
#This is contributed by ishan0202


C#




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
 
public class Gfg
{
    // Function to check whether all the array
// elements can be made to 0.
    static void is_possible(int[] arr, int[] brr, int n, int m, int k)
    {
        // Initialize a vector of pairs v to
        // store the brr[i] and arr[i]
        List<Tuple<int, int>> v=new List<Tuple<int, int>>();
        int i;
        for (i = 0; i < n; i++) {
            v.Add(new Tuple<int, int>(brr[i] , arr[i]));
        }
     
        // Sort the vector v based on the first
        // element of the pair i.e brr[i]
        v.Sort();
        i = 0;
     
        // Initialize the value to be reduced
        // from arr[i] as sum = k
        int sum = k;
     
        // Iterate while k > 0 and i < n
        // and decay the value of k by v[i].
        // first and apply operation while
        // arr[i] which is v[i].second is > 0
        // also incrementing the sum by k
        while (k > 0 && i < n) {
            while ((v[i].Item2 - sum) > 0) {
     
                // Decay the value k
                k = k - v[i].Item1;
                if (k >= 0)
                    sum += k;
                else
                    break;
            }
            i++;
        }
     
        // Initialize ctr =0 to check whether
        // all the array elements of arr[]
        // are made to 0
        int ctr = 0;
        for (i=0 ; i<v.Count; i++) {
             
            if ((v[i].Item2 - sum) <= 0) {
                ctr++;
            }
        }
     
        // If all are made to 0 print YES
        // else print NO
        if (ctr == n) {
            Console.Write("YES\n");
        }
        else {
            Console.Write("NO\n");
        }
    }
     
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 18, 5, 13, 9, 10, 1 };
        int n = arr.Length;
        int[] arr2 = { 2, 7, 2, 1, 2, 6 };
        int m = arr2.Length;
        int K = 7;
        is_possible(arr, arr2, n, m, K);
     
        int[] brr = { 5, 5, 5 };
        int n2 = brr.Length;
        int[] brr2 = { 4, 4, 4 };
        int m2 = brr2.Length;
        int K2 = 4;
        is_possible(brr, brr2, n2, m2, K2);
    }
}


Javascript




function is_possible(arr, brr, n, m, k) {
    var v = []
    for (var i = 0; i < n; i++) {
        v.push({ brr: brr[i], arr: arr[i] });
    }
 
    v.sort(function (a, b) {
        return a.brr - b.brr;
    });
 
    var i = 0;
    var sum = k;
 
    while (k > 0 && i < n) {
        while ((v[i].arr - sum) > 0) {
            k = k - v[i].brr;
            if (k >= 0)
                sum += k;
            else
                break;
        }
        i++;
    }
 
    var ctr = 0;
    for (var itr of v) {
        if ((itr.arr - sum) <= 0) {
            ctr++;
        }
    }
 
    if (ctr == n) {
        console.log("YES");
    }
    else {
        console.log("NO");
    }
}
 
// Driver Code
console.log(is_possible([18, 5, 13, 9, 10, 1], [2, 7, 2, 1, 2, 6], 6, 6, 7));
console.log(is_possible([5, 5, 5], [4, 4, 4], 3, 3, 4));


Output

YES
NO

Time Complexity: O(NlogN), where N is the size of the array.
Auxiliary Space: O(N)

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads