Find the smallest sub array with a sum greater than a given number.
💻 coding

Find the smallest sub array with a sum greater than a given number.

1 min read 172 words
1 min read
ShareWhatsAppPost on X
  • 1The goal is to find the smallest subarray with a sum greater than a specified number.
  • 2An efficient algorithm with a time complexity of O(n) is required for this problem.
  • 3The provided Java solution uses a queue to track elements and calculate the minimum length of the subarray.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The goal is to find the smallest subarray with a sum greater than a specified number."

Find the smallest sub array with a sum greater than a given number.

You are given an array of integers and a particular number, you need to find the smallest subarray possible with a sum greater than the given Number. The requirement is to write an algorithm that calculates in Time Complexity of O(n).

Java Solution of the given problem is :

import java.util.LinkedList;
import java.util.Queue;

public class SmallestSubArrayWithSumGreaterThanNumber {
	public static void main(String[] args) {
		 int arr[] = {1, 4, 45, 6, 10, 19};
	 int x = 51;
	 
	 long startTime = System.nanoTime();
	 
	 int res = FindSmallestSubArrayWithSumGreater(arr,x);
	 if(res == arr.length + 1)
	 	 System.out.println("Not Available");
	 else
	 	 System.out.println(res);
	 
	 long endTime = System.nanoTime();
		long totalTime = endTime - startTime;
		System.out.println("Total Time (nanoseconds) : " + (totalTime));
	}

	private static int FindSmallestSubArrayWithSumGreater(int[] arr, int x) {
		
		Queue<Integer> queue = new LinkedList<Integer>();
		int sum = 0;
		int min_len = arr.length + 1;
		for(int i=0;i<arr.length;i++)
		{
			if(x < sum && min_len > queue.size()) {
				min_len = queue.size();
				sum -= (Integer) queue.remove();
			}
			else {
				sum += arr[i];
				queue.add(arr[i]);
			}
		}
		return min_len;
	}
}

Output:

3
Total Time (nanoseconds) : 665298

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 July 2018 · 1 min read · 172 words

Part of AskGif Blog · coding

You might also like