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;
        }
    }
}

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;
    }
}

All Problems

All Solutions