Suppose we have an array of n different second values. We have to check whether it is possible to start from 12'O clock and go back to 12 by only adding or subtracting the given seconds or not. We can use all given seconds exactly once, we can either add seconds or subtract it.
So, if the input is like seconds = [40,90,50], then the output will be True as it can add 40 then subtract 90 then again add 50.
To solve this, we will follow these steps −
- size := 2^(length of seconds array)
- for c in range 0 to size - 1, do
- add := 0
- for j in range 0 to size of seconds - 1, do
- if c AND (2^j) is non-zero, then
- add := add + seconds[j]
- otherwise,
- add := add - seconds[j]
- if c AND (2^j) is non-zero, then
- if add is divisible by (24 * 60), then
- return True
- return False
Example
Let us see the following implementation to get better understanding −
def solve(seconds): size = 2**len(seconds) for c in range(size): add = 0 for j in range(len(seconds)) : if c & (1 << j): add += seconds[j] else: add -= seconds[j] if add % (24 * 60) == 0: return True return False seconds = [40,90,50] print(solve(seconds))
Input
[40,90,50]
Output
True