#C13514. Longest Contiguous Subarray with Sum Constraint

    ID: 43061 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Sum Constraint

Longest Contiguous Subarray with Sum Constraint

You are given an array of integers and an integer \(k\). Your task is to find the longest contiguous subarray whose sum is less than or equal to \(k\). If there are multiple subarrays with the same maximum length, you should return the first one that appears in the array.

Detailed Explanation:

  • The input consists of an integer \(n\) denoting the number of elements in the array, an integer \(k\) representing the sum threshold, followed by \(n\) space-separated integers.
  • You need to determine the subarray (continuous segment) with the maximum length such that the sum of its elements does not exceed \(k\).
  • If no subarray satisfies the condition, the output should be empty.

Examples:

  • For the array [1, 2, 3, 4, 5] with \(k = 10\), the longest valid subarray is [1, 2, 3, 4].
  • For the array [4, 6, 1, 2, 3] with \(k = 5\), the longest valid subarray is [1, 2].

inputFormat

The first line contains two integers \(n\) and \(k\), where \(n\) is the number of elements in the array and \(k\) is the maximum allowed sum.

The second line contains \(n\) space-separated integers representing the array elements.

outputFormat

Output a single line containing the longest contiguous subarray (elements separated by a single space) whose sum is less than or equal to \(k\). If no such subarray exists, output an empty line.

## sample
5 10
1 2 3 4 5
1 2 3 4