# Check if all people can vote on two machines in Python

Suppose we have a number n denotes n people and there are two identical voting machines. We also have an array called time of size n such that time[i] represents total time spent by i-th person to vote on any machine. At one time instant, only one person can be there on each of the two machines. We also have another value x, representing the maximum allowable time for which machines are operational, we have to check whether all persons can place their vote or not.

So, if the input is like n = 3, x = 7, time = [3, 5, 3], then the output will be True. Because at time t0 the 0th person go to the first machine and 1st person go to the second machine. Now at time t3 first machine is free. Now 2nd person go to first machine and at time t5 second machine is free and at time t6 first machine is free so all participants have voted in time.

To solve this, we will follow these steps −

• total_sum := sum of all elements of time
• if total_sum <= x, then
• return True
• sort the list time
• prev_sum := an array of size same as time and fill with 0
• prev_sum[0] := time[0]
• for i in range 1 to size of prev_sum, do
• prev_sum[i] := prev_sum[i - 1] + time[i]
• for i in range 0 to size of prev_sum, do
• for j in range i + 1 to size of prev_sum - 1, do
• temp_sum := prev_sum[i] + (total_sum - prev_sum[j])
• if temp_sum <= x and total_sum - temp_sum <= x, then
• return True
• return False

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(n, x, time):
total_sum = sum(time)
if total_sum <= x:
return True
time.sort()
prev_sum = [0 for i in range(len(time))]
prev_sum[0] = time[0]
for i in range(1, len(prev_sum)):
prev_sum[i] = prev_sum[i - 1] + time[i]
for i in range(0, len(prev_sum)):
for j in range(i + 1, len(prev_sum)):
temp_sum = (prev_sum[i] + (total_sum - prev_sum[j]))
if temp_sum <= x and total_sum - temp_sum <= x:
return True
return False
n = 3
x = 7
time = [3, 5, 3]
print(solve(n, x, time))

## Input

3, 7, [3, 5, 3]

## Output

True