Given an array arr[] of measurement N, the duty is to calculate the minimal variety of parts to be faraway from the array such that the sum of the remaining array parts is divisible by 3.

Examples:

Enter:  N = 3, arr[] = {1, 2, 3}
Output: 0
Rationalization: 1+2+3 = 6 and it’s already divisible by 3. 
So we have to take away 0 parts.

Enter: N = 4, arr[] = {3, 6, 2, 2}
Output: 2
Rationalization: 3+6+2+2 = 13. 
On eradicating final two parts, sum would turn into 9 which is divisible by 3. 
That is minimal variety of parts to be eliminated.

 

Strategy: The answer to the issue is predicated on the next mathematical concept:

  • If the sum is already divisible by 3, no deletions required.
  • If sumpercent3 = 1 then take away both 1 component (say x) such that xpercent3 = 1 or two parts (say x and y) such that (xpercent2 = ypercent2 = 2) as a result of (2+2)%3 = 1.
  • If sumpercent2 = 2, then both take away a component (say x) in order that xpercent3 = 2 or take away two parts (say x, y) such that (xpercent2 = ypercent2 = 1) as a result of (1+1)%3 = 2 

Observe the beneath steps to resolve this downside:

  • Calculate the sum of all of the array parts (say sum).
  • Traverse the array from i = 0 to N-1:
    • If the component is divisible by 3 improve the depend of parts divisible by 3.
    • Equally, retailer the depend of the weather which have the rest = 1 and a couple of when divided by 3.
  • Now discover the minimal variety of deletions required from the above talked about situations.

Beneath is the implementation of the above strategy.

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int func(int arr[], int n)

{

    int sum = 0;

    int twomod3 = 0, onemod3 = 0;

    for (int i = 0; i < n; i++) {

  

        

        sum += arr[i];

  

        

        

        

        if (arr[i] % 3 == 2)

            twomod3++;

  

        

        

        

        else if (arr[i] % 3 == 1)

            onemod3++;

    }

  

    

    int ans = n;

  

    

    if (sum % 3 == 0)

        ans = 0;

  

    else if (sum % 3 == 1) {

        

        

        if (onemod3 >= 1) {

            ans = 1;

        }

  

        

        

        else if (twomod3 >= 2) {

            ans = 2;

        }

    }

    else {

        

        

        if (twomod3 >= 1) {

            ans = 1;

        }

        

        

        else if (onemod3 >= 2) {

            ans = 2;

        }

    }

    ans = min(ans, n);

    return ans;

}

  

int essential()

{

    int arr[] = { 3, 6, 2, 2 };

    int N = sizeof(arr) / sizeof(arr[0]);

  

    

    int ans = func(arr, N);

    cout << ans;

    return 0;

}

Time Complexity: O(N)
Auxiliary House: O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here