Problem Statement

N light bulbs are connected by a wire.

Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb.

Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs.

You can press the same switch multiple times.

Note : 0 represents the bulb is off and 1 represents the bulb is on.

Input Format:

The first and the only argument contains an integer array A, of size N.

Output Format:

Return an integer representing the minimum number of switches required.

Constraints:

1 <= N <= 5e5 0 <= A[i] <= 1

Example:

`Input 1: A = [1]

Output 1: 0

Explanation 1: There is no need to turn any switches as all the bulbs are already on.

Input 2: A = [0 1 0 1]

Output 2: 4

Explanation 2: press switch 0 : [1 0 1 0] press switch 1 : [1 1 0 1] press switch 2 : [1 1 1 0] press switch 3 : [1 1 1 1]`

Problem Link

Bulbs - InterviewBit

Code

// CPP program to find number switch presses to
// turn all bulbs on.
#include<bits/stdc++.h>
using namespace std;

int bulbs(int a[],int n)
{
	// To keep track of switch presses so far
	int count = 0;

	int res = 0;
	for (int i = 0; i < n; i++)
	{
		/* if the bulb's original state is on and count
		is even, it is currently on...*/
		/* no need to press this switch */
		if (a[i] == 1 && count % 2 == 0)
			continue;

		/* If the bulb's original state is off and count
		is odd, it is currently on...*/
		/* no need to press this switch */
		else if(a[i] == 0 && count % 2 != 0)
			continue;

		/* if the bulb's original state is on and count	
		is odd, it is currently off...*/
		/* Press this switch to on the bulb and increase
		the count */
		else if (a[i] == 1 && count % 2 != 0)
		{
			res++;
			count++;
		}
		
		/* if the bulb's original state is off and
		count is even, it is currently off...*/
		/* press this switch to on the bulb and
		increase the count */
		else if (a[i] == 0 && count % 2 == 0)
		{
			res++;
			count++;
		}
	}
	return res;
}

// Driver code
int main()
{
	int states[] = {0,1,0,1};
	int n = sizeof(states)/sizeof(states[0]);
	cout << "The minimum number of switches needed are " << bulbs(states,n);
}

// This code is contributed by
// Sanjit_Prasad