BackmediumArrays

Longest Subarray with Exact Average Solution

Problem Statement

You are given an array of integers `nums` and an integer `k`. Find the maximum length of a contiguous subarray such that the mathematical average of its elements is exactly equal to `k`. If no such subarray exists, return 0.

Example 1
Input
nums = [1, 3, 2, 6, -1], k = 3
Output
4

Explanation: The subarray [1, 3, 2, 6] has a sum of 12. Its length is 4, making the average 12 / 4 = 3, which equals k. This is the longest valid subarray.

Example 2
Input
nums = [2, 2, 2], k = 4
Output
0

Explanation: No contiguous subarray has elements that average to 4.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= k <= 10^4
Live Compiler
Sign InSign Up
Loading...
Test Cases & Output
Click "Run" to execute