Skip to content

Commit 50717d0

Browse files
committed
Minimum Lights to Activate
1 parent fec6ade commit 50717d0

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/minimum-lights-to-activate/
3+
4+
Problem Description
5+
There is a corridor in a Jail which is N units long. Given an array A of size N. The ith index of this array is 0
6+
if the light at ith position is faulty otherwise it is 1.
7+
All the lights are of specific power B which if is placed at position X, it can light the corridor from [ X-B+1, X+B-1].
8+
Initially all lights are off.
9+
Return the minimum number of lights to be turned ON to light the whole corridor or -1 if the whole corridor cannot be lighted.
10+
11+
Problem Constraints
12+
1 <= N <= 1000
13+
1 <= B <= 1000
14+
15+
Input Format
16+
First argument is an integer array A where A[i] is either 0 or 1.
17+
Second argument is an integer B.
18+
19+
Output Format
20+
Return the minimum number of lights to be turned ON to light the whole corridor or -1 if the whole corridor cannot be lighted.
21+
22+
23+
Example Input
24+
Input 1:
25+
A = [ 0, 0, 1, 1, 1, 0, 0, 1].
26+
B = 3
27+
28+
Input 2:
29+
A = [ 0, 0, 0, 1, 0].
30+
B = 3
31+
32+
Example Output
33+
Output 1:
34+
2
35+
36+
Output 2:
37+
-1
38+
39+
Example Explanation
40+
Explanation 1:
41+
In the first configuration, Turn on the lights at 3rd and 8th index.
42+
Light at 3rd index covers from [ 1, 5] and light at 8th index covers [ 6, 8].
43+
44+
Explanation 2:
45+
In the second configuration, there is no light which can light the first corridor.
46+
"""
47+
class Solution:
48+
# @param A : list of integers
49+
# @param B : integer
50+
# @return an integer
51+
def solve(self, A, B):
52+
n = len(A)
53+
ans = 0
54+
last = -1
55+
while (last < n - 1):
56+
pos = -1
57+
end = max(-1,last - B + 1)
58+
start = min(n-1,last + B)
59+
for i in range( start, end , -1):
60+
if (A[i] == 1 and i - B <= last):
61+
pos = i;
62+
break;
63+
64+
65+
if (pos == -1):
66+
return -1
67+
68+
ans = ans + 1
69+
last = pos + B - 1
70+
71+
return ans

0 commit comments

Comments
 (0)