Subarray Division 1

  • + 0 comments

    Java - O(n)

        public static int birthday(List<Integer> s, int d, int m) {
            int count = 0;   // current sum of the window
            int steps = 0;   // current window size
            int total = 0;   // total valid segments
    
            for (int i = 0; i < s.size(); i++) {
                steps++;
                count += s.get(i);
    
                if (steps == m) {
                    if (count == d) {
                        total++;
                    }
    
                    // Instead of resetting, slide the window
                    count -= s.get(i - m + 1); // remove oldest element
                    steps--;                   // shrink window by 1
                }
            }
            return total;
        }