Number of subarrays having absolute sum greater than K | Set-2
Last Updated :
07 Dec, 2022
Given an integer array arr[] of length N consisting of both positive and negative integers, the task is to find the number of sub-arrays with the absolute value of sum greater than a given positive number K.
Examples:
Input : arr[] = {-1, 0, 1}, K = 0
Output : 4
All possible sub-arrays and there total sum:
{-1} = -1
{0} = 0
{1} = 1
{-1, 0} = -1
{0, 1} = 1
{-1, 0, 1} = 0
Thus, 4 sub-arrays have absolute
value of sum greater than 0.
Input : arr[] = {2, 3, 4}, K = 4
Output : 3
Approach: A similar approach that works on a positive integer array is discussed here.
In this article, we will look at an algorithm that solves this problem for both positive and negative integers.
- Create a prefix-sum array of the given array.
- Sort the prefix-sum array.
- Create variable ans, find the number of elements in the prefix-sum array with value lesser than -K or greater than K, and initialize ans with this value.
- Now, iterate the sorted prefix-sum array and for every index i, find the index of the first element with a value greater than arr[i] + K. Let's say this index is j.
Then ans can be updated as ans += N - j as the number of elements in the prefix-sum array larger than the value of arr[i]+K will be equal to N - j.
To find the index j, perform binary search on prefix-sum array. Specifically, find the upper-bound on the value of prefix-sum[i] + k.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
#define maxLen 30
using namespace std;
// Function to find required value
int findCnt(int arr[], int n, int k)
{
// Variable to store final answer
int ans = 0;
// Loop to find prefix-sum
for (int i = 1; i < n; i++) {
arr[i] += arr[i - 1];
if (arr[i] > k or arr[i] < -1 * k)
ans++;
}
if (arr[0] > k || arr[0] < -1 * k)
ans++;
// Sorting prefix-sum array
sort(arr, arr + n);
// Loop to find upper_bound
// for each element
for (int i = 0; i < n; i++)
ans += n -
(upper_bound(arr, arr + n, arr[i] + k) - arr);
// Returning final answer
return ans;
}
// Driver code
int main()
{
int arr[] = { -1, 4, -5, 6 };
int n = sizeof(arr) / sizeof(int);
int k = 0;
// Function to find required value
cout << findCnt(arr, n, k);
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
static int maxLen = 30;
// Function to find required value
static int findCnt(int arr[], int n, int k)
{
// Variable to store final answer
int ans = 0;
// Loop to find prefix-sum
for (int i = 1; i < n; i++)
{
arr[i] += arr[i - 1];
if (arr[i] > k || arr[i] < -1 * k)
ans++;
}
if (arr[0] > k || arr[0] < -1 * k)
ans++;
// Sorting prefix-sum array
Arrays.sort(arr);
// Loop to find upper_bound
// for each element
for (int i = 0; i < n; i++)
ans += n - upper_bound(arr, 0, n, arr[i] + k);
// Returning final answer
return ans;
}
static int upper_bound(int[] a, int low,
int high, int element)
{
while(low < high)
{
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { -1, 4, -5, 6 };
int n = arr.length;
int k = 0;
// Function to find required value
System.out.println(findCnt(arr, n, k));
}
}
// This code is contributed by 29AjayKumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find required value
static int findCnt(int []arr, int n, int k)
{
// Variable to store final answer
int ans = 0;
// Loop to find prefix-sum
for (int i = 1; i < n; i++)
{
arr[i] += arr[i - 1];
if (arr[i] > k || arr[i] < -1 * k)
ans++;
}
if (arr[0] > k || arr[0] < -1 * k)
ans++;
// Sorting prefix-sum array
Array.Sort(arr);
// Loop to find upper_bound
// for each element
for (int i = 0; i < n; i++)
ans += n - upper_bound(arr, 0, n, arr[i] + k);
// Returning final answer
return ans;
}
static int upper_bound(int[] a, int low,
int high, int element)
{
while(low < high)
{
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver code
public static void Main()
{
int []arr = { -1, 4, -5, 6 };
int n = arr.Length;
int k = 0;
// Function to find required value
Console.WriteLine(findCnt(arr, n, k));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the above approach
from bisect import bisect as upper_bound
maxLen=30
# Function to find required value
def findCnt(arr, n, k):
# Variable to store final answer
ans = 0
# Loop to find prefix-sum
for i in range(1,n):
arr[i] += arr[i - 1]
if (arr[i] > k or arr[i] < -1 * k):
ans+=1
if (arr[0] > k or arr[0] < -1 * k):
ans+=1
# Sorting prefix-sum array
arr=sorted(arr)
# Loop to find upper_bound
# for each element
for i in range(n):
ans += n - upper_bound(arr,arr[i] + k)
# Returning final answer
return ans
# Driver code
arr = [-1, 4, -5, 6]
n = len(arr)
k = 0
# Function to find required value
print(findCnt(arr, n, k))
# This code is contributed by mohit kumar 29
JavaScript
<script>
// Javascript implementation of the above approach
var maxLen = 30;
function upper_bound(a, low, high, element)
{
while(low < high)
{
var middle = low + parseInt((high - low)/2);
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Function to find required value
function findCnt(arr, n, k)
{
// Variable to store final answer
var ans = 0;
// Loop to find prefix-sum
for (var i = 1; i < n; i++) {
arr[i] += arr[i - 1];
if (arr[i] > k || arr[i] < -1 * k)
ans++;
}
if (arr[0] > k || arr[0] < -1 * k)
ans++;
// Sorting prefix-sum array
arr.sort((a,b)=>a-b)
// Loop to find upper_bound
// for each element
for (var i = 0; i < n; i++)
ans += (n - upper_bound(arr, 0, n, arr[i] + k));
// Returning final answer
return ans;
}
// Driver code
var arr = [ -1, 4, -5, 6 ];
var n = arr.length;
var k = 0;
// Function to find required value
document.write( findCnt(arr, n, k));
</script>
Time complexity : O(Nlog(N))
Auxiliary Space: O(1), no extra space is required, so it is a constant
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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