1052. Grumpy Bookstore Owner

T: O(n)
S: O(1)
class Solution {
    public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
        int left = 0;
        int max = 0;
        int cur = 0;
        int maxLeftIdx = 0;
        int n = customers.length;
        for (int right = 0; right < n; right++) {
            if (grumpy[right] == 1) {
                cur += customers[right];
            }
            
            if (right == left + minutes - 1) {
                if (cur > max) {
                    max = cur;
                    maxLeftIdx = left;
                }
                if (grumpy[left] == 1) {
                    cur -= customers[left];
                }
                left++;
            }
        }

        for (int i = maxLeftIdx; i < maxLeftIdx+minutes; i++) {
            grumpy[i] = 0;
        }
        int result = 0;
        for (int i = 0; i < n; i++) {
            if (grumpy[i] == 0) {
                result += customers[i];
            }
        }
        return result;
    }
}

/**
[1,0,1,2,1,1,7,5], grumpy = 
[0,1,0,1,0,1,0,1], minutes = 3
[.    ]

[1,0,1,2,1,1,7,5]
 1 1 2 4 5 6 13 18
 0 1 0 1 0 1 0  1

using sliding win to calculate max grumsy numbers


T: O(n)
S: O(1)

 */

Last updated