Subarray Division 1

  • + 0 comments

    Java solution using a Queue:

        public static int birthday(List<Integer> s, int d, int m) {
            int count = 0, currentSum=0;
            ArrayList<Integer> candidates = new ArrayList<>();
            // Initial items
            for(int i=0;i < m;i++){
                candidates.add(s.get(i));
                currentSum += s.get(i);
            }
            //Check if satisfies the solution
            if(currentSum == d) count++;
            // m - 1 as I already have the first 3 items
            for(int i=m; i < s.size();i++){
                //Substract candidates[0] from sum
                currentSum -= candidates.remove(0);
                //Enqueue new item
                candidates.add(s.get(i));
                //Add new item to sum
                currentSum += s.get(i);  
                //Check if satisfies the solution
                if(currentSum == d) count++;          
            }
            return count;
            
        }