There are n people and two identical voting machines. We are also given an array a[] of size n such that a[i] stores time required by i-th person to go to any machine, mark his vote and come back. At one time instant, only one person can be there on each of the machines. Given a value x, defining the maximum allowable time for which machines are operational, check whether all persons can cast their vote or not.
Examples:Â
Input : n = 3, x = 4
a[] = {2, 4, 2}
Output: YES
There are n = 3 persons say and maximum
allowed time is x = 4 units. Let the persons
be P0, P1, and P2 and two machines be M0 and M1.
At t0: P0 goes to M0
At t0: P1 goes to M1
At t2: M0 is free, P2 goes to M0
At t4: both M0 and M1 are free and all 3 have
given their vote.
Method 1Â
Let sum be the total time taken by all n people. If sum <=x, then answer will obviously be YES. Otherwise, we need to check whether the given array can be split into two parts such that the sum of the first part and sum of the second part are both less than or equal to x. The problem is similar to the knapsack problem. Imagine two knapsacks each with capacity x. Now find, maximum people who can vote on any one machine i.e. find maximum subset sum for a knapsack of capacity x. Let this sum be s1. Now if (sum-s1) <= x, then answer is YES else answer is NO.
C++
// C++ program to check if all people can// vote using two machines within limited// time#include<bits/stdc++.h>using namespace std;Â
// Returns true if n people can vote using// two machines in x time.bool canVote(int a[], int n, int x){    // dp[i][j] stores maximum possible number    // of people among arr[0..i-1] can vote    // in j time.    int dp[n+1][x+1];    memset(dp, 0, sizeof(dp));Â
    // Find sum of all times    int sum = 0;    for (int i=0; i<=n; i++ )        sum += a[i];Â
    // Fill dp[][] in bottom up manner (Similar    // to knapsack).    for (int i=1; i<=n; i++)        for (int j=1; j<=x; j++)            if (a[i] <= j)                dp[i][j] = max(dp[i-1][j],                        a[i] + dp[i-1][j-a[i]]);            else                dp[i][j] = dp[i-1][j];Â
    // If remaining people can go to other machine.    return (sum - dp[n][x] <= x);}Â
// Driver codeint main(){Â Â Â Â int n = 3, x = 4;Â Â Â Â int a[] = {2, 4, 2};Â Â Â Â canVote(a, n, x)? cout << "YES\n" :Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â cout << "NO\n";Â Â Â Â return 0;} |
Java
// Java program to check if all people can// vote using two machines within limited// timepublic class Main{    // Returns true if n people can vote using    // two machines in x time.    static boolean canVote(int[] a, int n, int x)    {        // dp[i][j] stores maximum possible number        // of people among arr[0..i-1] can vote        // in j time.        int[][] dp = new int[n + 1][x + 1];        for(int i = 0; i < n + 1; i++)        {            for(int j = 0; j < x + 1; j++)            {                dp[i][j] = 0;            }        }               // Find sum of all times        int sum = 0;        for (int i = 0; i < n; i++ )            sum += a[i];               // Fill dp[][] in bottom up manner (Similar        // to knapsack).        for (int i = 1; i < n; i++)            for (int j = 1; j <= x; j++)                if (a[i] <= j)                    dp[i][j] = Math.max(dp[i - 1][j], a[i] + dp[i - 1][j - a[i]]);                else                    dp[i][j] = dp[i - 1][j];               // If remaining people can go to other machine.        return (sum - dp[n][x] >= x);    }         public static void main(String[] args) {        int n = 3, x = 4;        int[] a = {2, 4, 2};        if(canVote(a, n, x))        {            System.out.println("YES");        }        else{            System.out.println("NO");        }    }}Â
// This code is contributed by mukesh07. |
Python3
# Python3 program to check if all people can# vote using two machines within limited# timeÂ
# Function returns true if n people can vote # using two machines in x time.def canVote(a, n, x):         # dp[i][j] stores maximum possible number    # of people among arr[0..i-1] can vote    # in j time.    dp = [[0] * (x + 1) for _ in range(n + 1)]    a = a[:]    a.append(0)Â
    # Find sum of all times    sm = 0    for i in range(n + 1):        sm += a[i]Â
    # Fill dp[][] in bottom up manner     # (Similar to knapsack).    for i in range(1, n + 1):        for j in range(1, x + 1):            if a[i] <= j:                dp[i][j] = max(dp[i - 1][j], a[i] +                               dp[i - 1][j - a[i]])            else:                dp[i][j] = dp[i - 1][j]Â
    # If remaining people can go to other machine.    return (sm - dp[n][x]) <= xÂ
# Driver Codeif __name__ == "__main__":Â Â Â Â n = 3Â Â Â Â x = 4Â Â Â Â a = [2, 4, 2]Â Â Â Â print("YES" if canVote(a, n, x) else "NO")Â
# This code is contributed # by vibhu4agarwal |
C#
// C# program to check if all people can// vote using two machines within limited// timeusing System;class GFG {         // Returns true if n people can vote using    // two machines in x time.    static bool canVote(int[] a, int n, int x)    {        // dp[i][j] stores maximum possible number        // of people among arr[0..i-1] can vote        // in j time.        int[,] dp = new int[n + 1, x + 1];        for(int i = 0; i < n + 1; i++)        {            for(int j = 0; j < x + 1; j++)            {                dp[i, j] = 0;            }        }              // Find sum of all times        int sum = 0;        for (int i = 0; i < n; i++ )            sum += a[i];              // Fill dp[][] in bottom up manner (Similar        // to knapsack).        for (int i = 1; i < n; i++)            for (int j = 1; j <= x; j++)                if (a[i] <= j)                    dp[i, j] = Math.Max(dp[i - 1, j],                            a[i] + dp[i - 1, j - a[i]]);                else                    dp[i, j] = dp[i - 1, j];              // If remaining people can go to other machine.        return (sum - dp[n, x] >= x);    }Â
  // Driver code  static void Main()  {    int n = 3, x = 4;    int[] a = {2, 4, 2};    if(canVote(a, n, x))    {        Console.Write("YES");    }    else{        Console.Write("NO");    }  }}Â
// This code is contributed by rameshtravel07. |
Javascript
<script>    // Javascript program to check if all people can    // vote using two machines within limited    // time         // Returns true if n people can vote using    // two machines in x time.    function canVote(a, n, x)    {        // dp[i][j] stores maximum possible number        // of people among arr[0..i-1] can vote        // in j time.        let dp = new Array(n+1);        for(let i = 0; i < n + 1; i++)        {            dp[i] = new Array(x + 1);            for(let j = 0; j < x+1; j++)            {                dp[i][j] = 0;            }        }Â
        // Find sum of all times        let sum = 0;        for (let i=0; i<n; i++ )            sum += a[i];Â
        // Fill dp[][] in bottom up manner (Similar        // to knapsack).        for (let i = 1; i <= n; i++)            for (let j = 1; j <= x; j++)                if (a[i] <= j)                    dp[i][j] = Math.max(dp[i-1][j],                            a[i] + dp[i-1][j-a[i]]);                else                    dp[i][j] = dp[i-1][j];Â
        // If remaining people can go to other machine.        return (sum - dp[n][x] <= x);    }         let n = 3, x = 4;    let a = [2, 4, 2];    if(canVote(a, n, x))    {        document.write("YES");    }    else{        document.write("NO");    }Â
// This code is contributed by decode2207.</script> |
YES
Time Complexity: O(x * n)Â
Auxiliary Space: O(x * n)
This article is contributed by Ekta Goel. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the neveropen main page and help other Geeks.
Method 2
The above method uses O(x * n) extra space, here we give a method that uses O(n) extra space.Â
Idea is to sort the array and then check if we can get any two array that can be a subarray which can be between the start and end of array such that its sum less than or equal to x and the sum of remaining elements is also less than x.Â
We use prefix sum for this purpose. We set i and j and check if sorted array between i to j – 1 gives sum <= x and the remaining elements also sum to sum <= x.
C++
// C++ program to check if all people can // vote using two machines within limited // time #include<bits/stdc++.h> using namespace std; Â
// Returns true if n people can vote using // two machines in x time. bool canVote(vector<int> a, int n, int x) {     // calculate total sum i.e total    // time taken by all people    int total_sum = 0;    for(auto x : a){        total_sum += x;    }         // if total time is less than x then    // all people can definitely vote    // hence return true    if(total_sum <= x)        return true;         // sort the vector    sort(a.begin(), a.end());         // declare a vector presum of same size    // as that of a and initialize it with 0    vector<int> presum(a.size(), 0);Â
    // prefixsum for first element    // will be element itself    presum[0] = a[0];    // fill the array    for(int i = 1; i < presum.size(); i++){        presum[i] = presum[i - 1] + a[i];    }Â
    // Set i and j and check if array     // from i to j - 1 gives sum <= x    for(int i = 0; i < presum.size(); i++){        for(int j = i + 1; j < presum.size(); j++){            int arr1_sum = (presum[i] +                            (total_sum - presum[j]));            if((arr1_sum <= x) &&                         (total_sum - arr1_sum) <= x)                return true;        }       }         return false;} Â
// Driver code int main() { Â Â Â Â int n = 3, x = 4; Â Â Â Â vector<int>a = {2, 4, 2}; Â Â Â Â canVote(a, n, x)? cout << "YES\n" : Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â cout << "NO\n"; Â Â Â Â return 0; } |
Java
// Java program to check if all people can// vote using two machines within limited// timeimport java.io.*;import java.util.*;Â
class GFG {    // Returns true if n people can vote using    // two machines in x time.    public static boolean canVote(int a[], int n, int x)    {        // calculate total sum i.e total        // time taken by all people        int total_sum = 0;        for (int z : a) {            total_sum += z;        }Â
        // if total time is less than x then        // all people can definitely vote        // hence return true        if (total_sum <= x)            return true;Â
        // sort the array        Arrays.sort(a);Â
        // declare a array presum of same size        // as that of a and initialize it with 0        int presum[] = new int[a.length];Â
        // prefixsum for first element        // will be element itself        presum[0] = a[0];        // fill the array        for (int i = 1; i < presum.length; i++) {            presum[i] = presum[i - 1] + a[i];        }Â
        // Set i and j and check if array        // from i to j - 1 gives sum <= x        for (int i = 0; i < presum.length; i++) {            for (int j = i + 1; j < presum.length; j++) {                int arr1_sum                    = (presum[i] + (total_sum - presum[j]));                if ((arr1_sum <= x)                    && (total_sum - arr1_sum) <= x)                    return true;            }        }Â
        return false;    }Â
    // Driver Code    public static void main(String[] args)    {        int n = 3, x = 4;        int a[] = { 2, 4, 2 };        if (canVote(a, n, x) == true)            System.out.println("YES");        else            System.out.println("NO");    }}Â
// This code is contributed by Rohit Pradhan |
Python3
# Python3 program to check if all people can # vote using two machines within limited # time Â
# Returns true if n people can vote using # two machines in x time. def canVote(a, n, x):Â
    # calculate total sum i.e total    # time taken by all people    total_sum = 0    for i in range(len(a)):        total_sum += a[i]         # if total time is less than x then    # all people can definitely vote    # hence return true    if(total_sum <= x):        return True         # sort the list    a.sort()         # declare a list presum of same size    # as that of a and initialize it with 0    presum = [0 for i in range(len(a))]Â
    # prefixsum for first element    # will be element itself    presum[0] = a[0]         # fill the array    for i in range(1, len(presum)):        presum[i] = presum[i - 1] + a[i]         # Set i and j and check if array     # from i to j - 1 gives sum <= x    for i in range(0, len(presum)):        for j in range(i + 1, len(presum)):            arr1_sum = (presum[i] + (total_sum - presum[j]))            if((arr1_sum <= x) and               (total_sum - arr1_sum) <= x):                return True         return FalseÂ
# Driver code n = 3x = 4a = [2, 4, 2] if(canVote(a, n, x)):Â Â Â Â print("YES")else:Â Â Â Â print("NO")Â
# This code is contributed by ashutosh450 |
C#
//C# code for the above approachusing System;using System.Linq;Â
class GFG{    // Returns true if n people can vote using    // two machines in x time.    public static bool CanVote(int[] a, int n, int x)    {        // calculate total sum i.e total        // time taken by all people        int total_sum = 0;        foreach (int z in a) {            total_sum += z;        }Â
        // if total time is less than x then        // all people can definitely vote        // hence return true        if (total_sum <= x)            return true;Â
        // sort the array        Array.Sort(a);Â
        // declare a array presum of same size        // as that of a and initialize it with 0        int[] presum = new int[a.Length];Â
        // prefixsum for first element        // will be element itself        presum[0] = a[0];        // fill the array        for (int i = 1; i < presum.Length; i++) {            presum[i] = presum[i - 1] + a[i];        }Â
        // Set i and j and check if array        // from i to j - 1 gives sum <= x        for (int i = 0; i < presum.Length; i++) {            for (int j = i + 1; j < presum.Length; j++) {                int arr1_sum                    = (presum[i] + (total_sum - presum[j]));                if ((arr1_sum <= x)                    && (total_sum - arr1_sum) <= x)                    return true;            }        }Â
        return false;    }Â
    // Driver Code    public static void Main(string[] args)    {        int n = 3;        int x = 4;        int[] a = { 2, 4, 2 };        if (CanVote(a, n, x) == true)            Console.WriteLine("YES");        else            Console.WriteLine("NO");    }}Â
//This code is contributed by ik_9 |
Javascript
// Returns true if n people can vote using // two machines in x time. function canVote(a, n, x) {Â
    // calculate total sum i.e total    // time taken by all people    let total_sum = 0;    for(let x of a){        total_sum += x;    }         // if total time is less than x then    // all people can definitely vote    // hence return true    if(total_sum <= x)        return true;         // sort the array    a.sort((a, b) => a - b);         // declare a array presum of same size    // as that of a and initialize it with 0    let presum = new Array(a.length).fill(0);Â
    // prefixsum for first element    // will be element itself    presum[0] = a[0];         // fill the array    for(let i = 1; i < presum.length; i++){        presum[i] = presum[i - 1] + a[i];    }Â
    // Set i and j and check if array     // from i to j - 1 gives sum <= x    for(let i = 0; i < presum.length; i++){        for(let j = i + 1; j < presum.length; j++){            let arr1_sum = (presum[i] +                            (total_sum - presum[j]));            if((arr1_sum <= x) &&                         (total_sum - arr1_sum) <= x)                return true;        }       }         return false;} Â
// Driver code let n = 3, x = 4; let a = [2, 4, 2]; console.log(canVote(a, n, x) ? "YES" : "NO");Â
// This code is contributed by unstoppablepandu. |
YES
Time Complexity: O(n * n)Â // since two loops are nested inside each other the have a time complexity of n*n
Auxiliary Space: O(n) // since an extra vector of size equal to the length of the array
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Info on that Topic: geeksforgeeks.org/check-if-all-people-can-vote-on-two-machines/ […]
… [Trackback]
[…] Info to that Topic: geeksforgeeks.org/check-if-all-people-can-vote-on-two-machines/ […]