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.

 

Example 1:

Input: light = [2,1,3,5,4]
Output: 3
Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4.

Example 2:

Input: light = [3,2,4,1,5]
Output: 2
Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0).

Example 3:

Input: light = [4,1,2,3]
Output: 1
Explanation: All bulbs turned on, are blue at the moment 3 (index-0).
Bulb 4th changes to blue at the moment 3.

Example 4:

Input: light = [2,1,4,3,6,5]
Output: 3

Example 5:

Input: light = [1,2,3,4,5,6]
Output: 6

 

Constraints:


Solution:

class Solution {
    static class BIT {
        int[] arr;
        
        public BIT(int n) {
            arr = new int[n + 1];
        }
        
        public void update(int index, int val) {
            index ++;
            while (index < arr.length) {
                arr[index] += val;
                index += index & (-index);
            }
        }
        
        public int sum(int index) {
            index ++;
            int res = 0;
            while (index > 0) {
                res += arr[index];
                index -= index & (-index);
            }
            return res;
        }
    }
    
    public int numTimesAllBlue(int[] light) {
        int n = light.length;
        BIT bit = new BIT(n);
        int count = 0, maxIndex = 0;
        for (int i = 0; i < n; i ++) {
            int l = light[i] - 1;
            maxIndex = Math.max(maxIndex, l);
            bit.update(l, 1);
            // System.out.println(Arrays.toString(bit.arr));
            // System.out.println(bit.sum(maxIndex) + ", " + (maxIndex + 1));
            if (bit.sum(maxIndex) == maxIndex + 1) {
                count ++;
            }
        }
        return count;
    }
}