Given an array of positive and negative integers and an integer K. The task is to find the subarray which has its sum closest to k. In case of multiple answers, print any one.

**Note:** Closest here means abs(sum-k) should be minimal.

**Examples:**

Input:a[] = { -5, 12, -3, 4, -15, 6, 1 }, K = 2

Output:1

The subarray {-3, 4} or {1} has sum = 1 which is the closest to K.

Input:a[] = { 2, 2, -1, 5, -3, -2 }, K = 7

Output:6

Here the output can be 6 or 8

The subarray {2, 2, -1, 5} gives sum as 8 which has abs(8-7) = 1 which is same as that of the subarray {2, -1, 5} which has abs(6-7) = 1.

A **naive approach** is to check for all possible subarray sum using prefix sum. The complexity in that case will be O(N^{2}).

An **efficient solution** will be to use C++ STL set and binary search to solve the following problem. Follow the below algorithm to solve the above problem.

- Initially insert the first element in the set container.
- Initiallize the answer
*sum*as first element and*difference*as abs(A_{0}-k). - Iterate for all array elements from 1 to N and keep adding the elements to prefix sum at each step to the set container.
- At every iteration, since the prefix sum is already there, we just need to subtract the sum of some elements from beginning to get the sum of any subarray. The greedy way will be to subtract the sum of the subarray which takes the sum closest to K.
- Using binary search (lower_bound() function can be used) find the sum of subarray from beginning which is closest to (prefix-k) as the subtraction of that number from prefix sum will give the subarray sum which is closest to K till that iteration.
- Also check for the index before which lower_bound() returns, since the sum can either be greater or lesser than K.
- If the lower_bound returns no such element, then the current prefix sum is compared and updated if it was lesser than the previous computed sum.

Below is the implementation of the above approach.

`// C++ program to find the ` `// sum of subarray whose sum is ` `// closest to K ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to find the sum of subarray ` `// whose sum is closest to K ` `int` `closestSubarraySumToK(` `int` `a[], ` `int` `n, ` `int` `k) ` `{ ` ` ` ` ` `// Declare a set ` ` ` `set<` `int` `> s; ` ` ` ` ` `// initially consider the ` ` ` `// first subarray as the first ` ` ` `// element in the array ` ` ` `int` `presum = a[0]; ` ` ` ` ` `// insert ` ` ` `s.insert(a[0]); ` ` ` ` ` `// Initially let this difference ` ` ` `// be the minimum ` ` ` `int` `mini = ` `abs` `(a[0] - k); ` ` ` ` ` `// let this be the sum ` ` ` `// of the subarray ` ` ` `// to be searched initially ` ` ` `int` `sum = presum; ` ` ` ` ` `// iterate for all the array elements ` ` ` `for` `(` `int` `i = 1; i < n; i++) { ` ` ` ` ` `// calculate the prefix sum ` ` ` `presum += a[i]; ` ` ` ` ` `// find the closest subarray ` ` ` `// sum to by using lower_bound ` ` ` `auto` `it = s.lower_bound(presum - k); ` ` ` ` ` `// if it is the first element ` ` ` `// in the set ` ` ` `if` `(it == s.begin()) { ` ` ` ` ` `// get the prefix sum till start ` ` ` `// of the subarray ` ` ` `int` `diff = *it; ` ` ` ` ` `// if the subarray sum is closest to K ` ` ` `// than the previous one ` ` ` `if` `(` `abs` `((presum - diff) - k) < mini) { ` ` ` ` ` `// update the minimal difference ` ` ` `mini = ` `abs` `((presum - diff) - k); ` ` ` ` ` `// update the sum ` ` ` `sum = presum - diff; ` ` ` `} ` ` ` `} ` ` ` ` ` `// if the difference is ` ` ` `// present in between ` ` ` `else` `if` `(it != s.end()) { ` ` ` ` ` `// get the prefix sum till start ` ` ` `// of the subarray ` ` ` `int` `diff = *it; ` ` ` ` ` `// if the subarray sum is closest to K ` ` ` `// than the previous one ` ` ` `if` `(` `abs` `((presum - diff) - k) < mini) { ` ` ` ` ` `// update the minimal difference ` ` ` `mini = ` `abs` `((presum - diff) - k); ` ` ` ` ` `// update the sum ` ` ` `sum = presum - diff; ` ` ` `} ` ` ` ` ` `// also check for the one before that ` ` ` `// since the sum can be greater than ` ` ` `// or less than K also ` ` ` `it--; ` ` ` ` ` `// get the prefix sum till start ` ` ` `// of the subarray ` ` ` `diff = *it; ` ` ` ` ` `// if the subarray sum is closest to K ` ` ` `// than the previous one ` ` ` `if` `(` `abs` `((presum - diff) - k) < mini) { ` ` ` ` ` `// update the minimal difference ` ` ` `mini = ` `abs` `((presum - diff) - k); ` ` ` ` ` `// update the sum ` ` ` `sum = presum - diff; ` ` ` `} ` ` ` `} ` ` ` ` ` `// if there exists no such prefix sum ` ` ` `// then the current prefix sum is ` ` ` `// checked and updated ` ` ` `else` `{ ` ` ` ` ` `// if the subarray sum is closest to K ` ` ` `// than the previous one ` ` ` `if` `(` `abs` `(presum - k) < mini) { ` ` ` ` ` `// update the minimal difference ` ` ` `mini = ` `abs` `(presum - k); ` ` ` ` ` `// update the sum ` ` ` `sum = presum; ` ` ` `} ` ` ` `} ` ` ` ` ` `// insert the current prefix sum ` ` ` `s.insert(presum); ` ` ` `} ` ` ` ` ` `return` `sum; ` `} ` ` ` `// Driver Code ` `int` `main() ` `{ ` ` ` `int` `a[] = { -5, 12, -3, 4, -15, 6, 1 }; ` ` ` `int` `n = ` `sizeof` `(a) / ` `sizeof` `(a[0]); ` ` ` `int` `k = 2; ` ` ` ` ` `cout << closestSubarraySumToK(a, n, k); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Time Complexity:** O(N log N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Subarray whose absolute sum is closest to K
- Two elements whose sum is closest to zero
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Find a triplet in an array whose sum is closest to a given number
- First subarray having sum at least half the maximum sum of any subarray of size K
- Maximize the subarray sum after multiplying all elements of any subarray with X
- Maximum length of subarray such that sum of the subarray is even
- Count of subarray that does not contain any subarray with sum 0
- Smallest subarray whose sum is multiple of array size
- Find a subarray whose sum is divisible by size of the array
- Length of longest subarray whose sum is not divisible by integer K
- Find a subarray of size K whose sum is a perfect square
- Find the Sub-array with sum closest to 0
- Subset with sum closest to zero
- Maximum sum subarray having sum less than or equal to given sum
- Maximum sum subarray having sum less than or equal to given sum using Set
- Maximum length of subarray such that all elements are equal in the subarray
- Length of largest subarray whose all elements are Perfect Number
- Length of largest subarray whose all elements Powerful number
- Longest subarray whose elements can be made equal by maximum K increments

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.