#K45082. Shortest Subarray with Sum at Least \(k\)

    ID: 27674 Type: Default 1000ms 256MiB

Shortest Subarray with Sum at Least \(k\)

Shortest Subarray with Sum at Least (k)

Given an array of \(n\) integers and an integer \(k\), your task is to determine the length of the shortest contiguous subarray such that the sum of its elements is at least \(k\). If no such subarray exists, return -1.

The problem can be formulated as follows:

Find the minimum length \(L\) for which there exists indices \(i\) and \(j\) (with \(0 \leq i \leq j < n\)) such that:

[ \sum_{t=i}^{j} nums[t] \geq k ]

If there is no subarray that satisfies the condition, output -1.

This problem requires efficient algorithms due to possible large input sizes.

inputFormat

The input is given via standard input (stdin) and has the following format:

n
num[0] num[1] ... num[n-1]
k

Where:

  • \(n\) is the number of elements in the array.
  • The next line (or same line separated by spaces) contains \(n\) integers representing the array elements.
  • \(k\) is the target sum.

outputFormat

Print the length of the shortest subarray whose sum is at least \(k\) to standard output (stdout). If no such subarray exists, print -1.

## sample
5
1 2 3 4 5
11
3