Minimum Size Subarray with Sum at Least k

medium Arrays

Problem

All numbers are positive. Print the smallest length of a contiguous part whose sum is at least k. Print 0 if no part has such a sum.

Constraints

  • 1 <= n <= 10^5
  • 1 <= a[i], k <= 10^9

Examples

Input

6
2 3 1 2 4 3
7

Output

2

Solutions

Best approachTime O(n)Space O(1)

The two pointers only move forward, so the total work is O(n) even though there is a loop inside a loop. This only works when all numbers are positive.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, n integers, then k.
 * Output  : The smallest length.
 * Approach: Variable sliding window.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a, int k) {
        // Step 1: A window [left, right] with its sum. All numbers are positive, so a bigger window has a bigger sum.
        int best = 0;
        int left = 0;
        long sum = 0;

        for (int right = 0; right < a.length; right++) {
            // Step 2: Add the new number on the right side.
            sum += a[right];

            // Step 3: While the sum is big enough, save the length and make the window smaller from the left.
            while (sum >= k) {
                int length = right - left + 1;
                if (best == 0 || length < best) {
                    best = length;
                }
                sum -= a[left];
                left++;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (1)
  1. Why must the numbers be positive?