703191. Consecutive Array Elements

Easy

Here is a detailed Markdown blog post for the "Consecutive Array Elements" problem:

Consecutive Array Elements Slug: consecutive-array-elements2711 Difficulty: Easy Id: 703191 Topic Tags: Arrays, Data Structures Company Tags: None

Summary

Given an array of integers, find the maximum number of consecutive elements that have a sum equal to the given target value. For example, if the input array is [1, 2, 3, 4, 5] and the target sum is 6, the output should be 2 because there are two consecutive elements ([2, 3]) in the array that sum up to 6.

Detailed Explanation

To solve this problem, we can use a sliding window approach. We initialize two pointers, left and right, to the start of the array. We also maintain a variable current_sum to keep track of the sum of elements in the current window.

We iterate through the array, moving the right pointer to the right and updating current_sum. Whenever current_sum equals the target value, we update our maximum count of consecutive elements.

Here's a step-by-step breakdown:

  1. Initialize left, right, and current_sum.
  2. Iterate through the array:
    • Move right to the right and update current_sum by adding the element at right.
    • If current_sum equals the target value, update our maximum count of consecutive elements.
  3. If current_sum exceeds the target value, move left to the right to reduce the sum and repeat step 2.

Time complexity: O(n), where n is the length of the input array. Space complexity: O(1), as we only use a few extra variables to store our state.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxConsecutive(int[] arr, int target) {
    int left = 0;
    int right = 0;
    int currentSum = 0;
    int maxCount = 0;

    while (right < arr.length) {
        currentSum += arr[right];
        if (currentSum == target) {
            maxCount = Math.max(maxCount, right - left + 1);
        } else if (currentSum > target) {
            currentSum -= arr[left++];
        }
        right++;
    }

    return maxCount;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.