Java

• /**
1375	Bulb Switcher III

There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right.
Initially, all the bulbs are turned off.

At moment k (for k from 0 to n - 1), we turn on the light[k] bulb.
A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too.

Return the number of moments in which all turned on bulbs are blue.
*/

public class Bulb_Switcher_III {
class Solution {
public int numTimesAllBlue(int[] light) {
int right = 0;
int count = 0;
for (int i = 0; i < light.length; i++) {
right = Math.max(right, light[i]);
if (right == i + 1) {
count++;
}
}
return count;
}
}
}

• // OJ: https://leetcode.com/problems/bulb-switcher-iii/
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
int numTimesAllBlue(vector<int>& A) {
int N = A.size(), ans = 0, on = 0, blue = 0;
vector<int> v(N, 0);
for (int n : A) {
int i = n - 1;
v[i] = 1;
on++;
while (i < N && v[i] > 0 && (i == 0 || v[i - 1] == 2)) {
if (v[i] == 1) blue++;
v[i++] = 2;
}
if (on == blue) ++ans;
}
return ans;
}
};

• print("Todo!")


Java

• class Solution {
public int numTimesAllBlue(int[] light) {
int count = 1;
int length = light.length;
int maxConsecutive = length - 1;
for (int i = length - 1; i > 0; i--) {
int turnOn = light[i];
maxConsecutive = Math.min(maxConsecutive, turnOn - 1);
if (maxConsecutive == i)
count++;
else if (maxConsecutive == 0)
break;
}
return count;
}
}

• // OJ: https://leetcode.com/problems/bulb-switcher-iii/
// Time: O(N^2)
// Space: O(1)
class Solution {
public:
int numTimesAllBlue(vector<int>& A) {
int N = A.size(), ans = 0, on = 0, blue = 0;
vector<int> v(N, 0);
for (int n : A) {
int i = n - 1;
v[i] = 1;
on++;
while (i < N && v[i] > 0 && (i == 0 || v[i - 1] == 2)) {
if (v[i] == 1) blue++;
v[i++] = 2;
}
if (on == blue) ++ans;
}
return ans;
}
};

• print("Todo!")