Subarray whose sum is closest to K
Last Updated :
14 Feb, 2025
Given an array of positive and negative integers and an integer K. The task is to find the subarray with its sum closest to k. In case of multiple answers, print anyone.
Note: Closest here means abs(sum-k) should be minimal.
Examples:
Input: arr[] = [ -5, 12, -3, 4, -15, 6, 1 ], k = 2
Output: 1
Explanation: The subarray {-3, 4} or {1} has sum = 1 which is the closest to k.
Input: arr[] = [ 2, 2, -1, 5, -3, -2 ], k = 7
Output: 6
Explanation: 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.
[Naive Approach] - Using Nested Loops - O(n ^ 2) Time and O(1) Space
The idea is to use nested loops to generate all possible subarrays and find the subarray with sum of its elements closest to k. The outer loop marks the starting of subarray and the inner loops marks the end.
Below is given the implementation:
C++
// Function to find the sum of subarray
// whose sum is closest to K
#include <bits/stdc++.h>
using namespace std;
int closestSubarraySumToK(vector<int>& arr, int k) {
// to store the minimum difference
int diff = INT_MAX;
// to store the answer
int ans = -1;
// generate sum of all possible subarrays
for (int i = 0; i < arr.size(); i++) {
// to store the sum of subarray
int sum = 0;
for (int j = i; j < arr.size(); j++) {
sum += arr[j];
if (abs(k - sum) < diff) {
diff = abs(k - sum);
ans = sum;
}
}
}
return ans;
}
// Driver Code
int main() {
vector<int> arr = {-5, 12, -3, 4, -15, 6, 1};
int k = 2;
cout << closestSubarraySumToK(arr, k) << endl;
return 0;
}
Java
// Java program to find the sum of subarray
// whose sum is closest to K
import java.util.*;
class GFG {
// Function to find the sum of subarray
// whose sum is closest to K
static int closestSubarraySumToK(List<Integer> arr, int k) {
// to store the minimum difference
int diff = Integer.MAX_VALUE;
// to store the answer
int ans = -1;
// generate sum of all possible subarrays
for (int i = 0; i < arr.size(); i++) {
// to store the sum of subarray
int sum = 0;
for (int j = i; j < arr.size(); j++) {
sum += arr.get(j);
if (Math.abs(k - sum) < diff) {
diff = Math.abs(k - sum);
ans = sum;
}
}
}
return ans;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(-5, 12, -3, 4, -15, 6, 1);
int k = 2;
System.out.println(closestSubarraySumToK(arr, k));
}
}
Python
# Python program to find the sum of subarray
# whose sum is closest to K
# Function to find the sum of subarray
# whose sum is closest to K
def closestSubarraySumToK(arr, k):
# to store the minimum difference
diff = float('inf')
# to store the answer
ans = -1
# generate sum of all possible subarrays
for i in range(len(arr)):
# to store the sum of subarray
sum = 0
for j in range(i, len(arr)):
sum += arr[j]
if abs(k - sum) < diff:
diff = abs(k - sum)
ans = sum
return ans
# Driver Code
arr = [-5, 12, -3, 4, -15, 6, 1]
k = 2
print(closestSubarraySumToK(arr, k))
C#
// C# program to find the sum of subarray
// whose sum is closest to K
using System;
using System.Collections.Generic;
class GFG {
// Function to find the sum of subarray
// whose sum is closest to K
static int ClosestSubarraySumToK(List<int> arr, int k) {
// to store the minimum difference
int diff = int.MaxValue;
// to store the answer
int ans = -1;
// generate sum of all possible subarrays
for (int i = 0; i < arr.Count; i++) {
// to store the sum of subarray
int sum = 0;
for (int j = i; j < arr.Count; j++) {
sum += arr[j];
if (Math.Abs(k - sum) < diff) {
diff = Math.Abs(k - sum);
ans = sum;
}
}
}
return ans;
}
// Driver Code
static void Main() {
List<int> arr = new List<int> { -5, 12, -3, 4, -15, 6, 1 };
int k = 2;
Console.WriteLine(ClosestSubarraySumToK(arr, k));
}
}
JavaScript
// JavaScript program to find the sum of subarray
// whose sum is closest to K
// Function to find the sum of subarray
// whose sum is closest to K
function closestSubarraySumToK(arr, k) {
// to store the minimum difference
let diff = Number.MAX_VALUE;
// to store the answer
let ans = -1;
// generate sum of all possible subarrays
for (let i = 0; i < arr.length; i++) {
// to store the sum of subarray
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
if (Math.abs(k - sum) < diff) {
diff = Math.abs(k - sum);
ans = sum;
}
}
}
return ans;
}
// Driver Code
let arr = [-5, 12, -3, 4, -15, 6, 1];
let k = 2;
console.log(closestSubarraySumToK(arr, k));
Time Complexity: O(n^2), as we are using nested loops two generate all possible subarrays.
Space Complexity: O(1)
[Expected Approach] - Using Tree Set - O(n * log n) Time and O(n) Space
- The idea is to use Tree Set (or Sorted Set) to store prefix sums in sorted order and use binary search to find the closest sum.
- Initialize the set by inserting the first element of array arr[], and iterate for all the elements and keep adding the sum to set.
- Now use binary search to find the prefix sum which is closest to (sum - k).
Below is the implementation of the above approach.
C++
// 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];
// insert the current prefix sum
s.insert(presum);
// find the closest subarray
// sum to by using lower_bound
auto it = s.lower_bound(presum - k);
// if k present in set
// return it
if (s.find(k) != s.end())
return 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 (abs(presum - 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;
}
}
}
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;
}
// This code is modified by Susobhan Akhuli
Java
// Java program to find the sum of subarray
// whose sum is closest to K
import java.util.*;
class GFG {
// Function to find the sum of subarray
// whose sum is closest to K
static int closestSubarraySumToK(List<Integer> arr, int k) {
int n = arr.size();
// Declare a set
TreeSet<Integer> s = new TreeSet<>();
// initially consider the
// first subarray as the first
// element in the array
int presum = arr.get(0);
// insert
s.add(arr.get(0));
// Initially let this difference
// be the minimum
int mini = Math.abs(arr.get(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 += arr.get(i);
// insert the current prefix sum
s.add(presum);
// find the closest subarray
// sum to by using ceiling (lower_bound in C++)
Integer it = s.ceiling(presum - k);
// if k present in set
// return it
if (s.contains(k))
return k;
// if it is the first element
// in the set
if (it == null) {
// if the subarray sum is closest to K
// than the previous one
if (Math.abs(presum - k) < mini) {
// update the minimal difference
mini = Math.abs(presum - k);
// update the sum
sum = presum;
}
} else {
// 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 (Math.abs((presum - diff) - k) < mini) {
// update the minimal difference
mini = Math.abs((presum - diff) - k);
// update the sum
sum = presum - diff;
}
// also check for the one before that
Integer itLower = s.lower(it);
if (itLower != null) {
diff = itLower;
if (Math.abs((presum - diff) - k) < mini) {
mini = Math.abs((presum - diff) - k);
sum = presum - diff;
}
}
}
}
return sum;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(-5, 12, -3, 4, -15, 6, 1);
int k = 2;
System.out.println(closestSubarraySumToK(arr, k));
}
}
Python
# Python program to find the sum of subarray
# whose sum is closest to K
import bisect
# Function to find the sum of subarray
# whose sum is closest to K
def closestSubarraySumToK(arr, k):
n = len(arr)
# Declare a sorted list
s = []
# initially consider the
# first subarray as the first
# element in the array
presum = arr[0]
# insert
s.append(arr[0])
# Initially let this difference
# be the minimum
mini = abs(arr[0] - k)
# let this be the sum
# of the subarray
# to be searched initially
sum = presum
# iterate for all the array elements
for i in range(1, n):
# calculate the prefix sum
presum += arr[i]
# insert the current prefix sum
bisect.insort(s, presum)
# find the closest subarray
# sum to by using bisect_right (lower_bound in C++)
pos = bisect.bisect_left(s, presum - k)
# if k present in set
# return it
if k in s:
return k
if pos < len(s):
diff = s[pos]
if abs((presum - diff) - k) < mini:
mini = abs((presum - diff) - k)
sum = presum - diff
if pos > 0:
diff = s[pos - 1]
if abs((presum - diff) - k) < mini:
mini = abs((presum - diff) - k)
sum = presum - diff
return sum
# Driver Code
arr = [-5, 12, -3, 4, -15, 6, 1]
k = 2
print(closestSubarraySumToK(arr, k))
C#
// C# program to find the sum of subarray
// whose sum is closest to K
using System;
using System.Collections.Generic;
class GFG {
// Function to find the sum of subarray
// whose sum is closest to K
static int ClosestSubarraySumToK(List<int> arr, int k) {
int n = arr.Count;
// Declare a sorted set
SortedSet<int> s = new SortedSet<int>();
// initially consider the
// first subarray as the first
// element in the array
int presum = arr[0];
// insert
s.Add(arr[0]);
// Initially let this difference
// be the minimum
int mini = Math.Abs(arr[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 += arr[i];
// insert the current prefix sum
s.Add(presum);
// find the closest subarray
// sum to by using GetViewBetween (lower_bound in C++)
int? it = s.GetViewBetween(presum - k, int.MaxValue).Min;
// if k present in set
// return it
if (s.Contains(k))
return k;
if (it.HasValue) {
int diff = it.Value;
if (Math.Abs((presum - diff) - k) < mini) {
mini = Math.Abs((presum - diff) - k);
sum = presum - diff;
}
}
// also check for the one before that
int? lower = s.GetViewBetween(int.MinValue, presum - k).Max;
if (lower.HasValue) {
int diff = lower.Value;
if (Math.Abs((presum - diff) - k) < mini) {
mini = Math.Abs((presum - diff) - k);
sum = presum - diff;
}
}
}
return sum;
}
static void Main() {
List<int> arr = new List<int> { -5, 12, -3, 4, -15, 6, 1 };
int k = 2;
Console.WriteLine(ClosestSubarraySumToK(arr, k));
}
}
JavaScript
// JavaScript program to find the sum of subarray
// whose sum is closest to K
class GFG {
// Function to find the sum of subarray
// whose sum is closest to K
static closestSubarraySumToK(arr, k) {
let n = arr.length;
// Declare a sorted set (simulated using an array)
let s = [];
// initially consider the
// first subarray as the first
// element in the array
let presum = arr[0];
// insert
s.push(arr[0]);
// Initially let this difference
// be the minimum
let mini = Math.abs(arr[0] - k);
// let this be the sum
// of the subarray
// to be searched initially
let sum = presum;
// iterate for all the array elements
for (let i = 1; i < n; i++) {
// calculate the prefix sum
presum += arr[i];
// insert the current prefix sum (keeping it sorted)
let index = this.lowerBound(s, presum);
s.splice(index, 0, presum);
// find the closest subarray
// sum to by using lower_bound
let itIndex = this.lowerBound(s, presum - k);
// if k present in set
// return it
if (s.includes(k))
return k;
// if it is the first element
// in the set
if (itIndex === 0) {
// get the prefix sum till start
// of the subarray
let diff = s[itIndex];
// if the subarray sum is closest to K
// than the previous one
if (Math.abs((presum - diff) - k) < mini) {
// update the minimal difference
mini = Math.abs((presum - diff) - k);
// update the sum
sum = presum - diff;
}
if (Math.abs(presum - k) < mini) {
mini = Math.abs(presum - k);
sum = presum;
}
}
// if the difference is
// present in between
else if (itIndex < s.length) {
// get the prefix sum till start
// of the subarray
let diff = s[itIndex];
// if the subarray sum is closest to K
// than the previous one
if (Math.abs((presum - diff) - k) < mini) {
// update the minimal difference
mini = Math.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
if (itIndex > 0) {
diff = s[itIndex - 1];
if (Math.abs((presum - diff) - k) < mini) {
mini = Math.abs((presum - diff) - k);
sum = presum - diff;
}
}
}
// if there exists no such prefix sum
// then the current prefix sum is
// checked and updated
else {
if (Math.abs(presum - k) < mini) {
mini = Math.abs(presum - k);
sum = presum;
}
}
}
return sum;
}
// Function to find the lower_bound (binary search)
static lowerBound(arr, target) {
let left = 0, right = arr.length;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}
}
// Driver Code
let arr = [-5, 12, -3, 4, -15, 6, 1];
let k = 2;
console.log(GFG.closestSubarraySumToK(arr, k));
Time Complexity:O(n log n). Binary search operating takes O(log n) Time, and we are performing binary search at each index, thus the overall time complexity will be O(n * log(n)).
Auxiliary Space: O(n), to store the prefix sum in the set.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem