Distinct Sub-array sum difference
Last Updated :
13 Sep, 2023
Given an array X[] of size N, then the task is to output the number of sub-arrays satisfying the given condition: The Sum of (X[i] – X[i+1]) in any sub-array from L to R(1<= L, R <= N) is not equal to X[R] – X[L].
Examples:
Input: N = 3, X[] = {20, 40, 60}
Output: 3
Explanation: There are three sub-arrays satisfying the given condition:
- X[1, 2] = (20 – 40) = -20, Which is not equal to (40 – 20) = 20.
- X[2, 3] = (40 – 60) = -20, Which is not equal to (60 – 40) = 20.
- X[1, 3] = (20 – 40) + (40 – 60) = -40, Which is not equal to (60 – 40) = 40. Hence, there are 3 sub-arrays.
Input: N = 5, X[] = {3, 4, 4, 5, 1}
Output: 9
Explanation: It can be verified that there are 9 sub-arrays satisfying the given conditions.
Approach: Implement the idea below to solve the problem
The problem is observation based and can be solved by using the HashMap data structure. For more clarification, see the Concept of Approach section below.
Concept of Approach:
- In this problem, one thing is to observe that if a subarray begins and ends with the same number, it won’t be considered an unstable subarray.
- So if the frequency of an element is greater than 1, and its frequency is F(say), so the number of non-unstable arrays contributed by that element is F*(F-1)/2.
- Calculate all possible non-unstable subarrays and subtract them from all possible subarrays.
Steps were taken to solve the problem:
- Create a HashMap let’s say Map.
- Traverse X[] and initialize the frequency of elements in the map.
- Create variable totalPairs and initialize it with N*(N-1)/2.
- Traverse the map using the loop and follow the below-mentioned steps under the scope of the loop:
- Create variable freq and initialize it with the frequency of the current element.
- Update freq as freq*(freq-1)/2.
- Subtract the value of freq from totalPairs. Formally, totalPairs-=freq.
- Return the value of totalPairs.
Below is the code to implement the approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long Max_SubArrays( int N, int X[])
{
unordered_map< int , int > map;
for ( int i = 0; i < N; i++) {
map[X[i]]++;
}
long long totalPair = N * (N - 1) / 2;
for ( auto it = map.begin(); it != map.end(); it++) {
long long freq = it->second;
long long pairwithNum = freq * (freq - 1) / 2;
totalPair -= pairwithNum;
}
return (totalPair);
}
int main()
{
int N = 5;
int X[] = { 3, 4, 4, 5, 1 };
cout << Max_SubArrays(N, X);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int N = 5 ;
int X[] = { 3 , 4 , 4 , 5 , 1 };
System.out.println(Max_SubArrays(N, X));
}
public static long Max_SubArrays( int N, int [] X)
{
HashMap<Integer, Integer> map = new HashMap<>();
for ( int i = 0 ; i < N; i++) {
map.put(X[i], map.getOrDefault(X[i], 0 ) + 1 );
}
long totalPair = N * (N - 1 ) / 2 ;
for (Map.Entry<Integer, Integer> entry :
map.entrySet()) {
long freq = entry.getValue();
long pairwithNum = freq * (freq - 1 ) / 2 ;
totalPair -= pairwithNum;
}
return (totalPair);
}
}
|
Python3
def Max_SubArrays(N, X):
map = {}
for i in range (N):
map [X[i]] = map .get(X[i], 0 ) + 1
total_pair = N * (N - 1 ) / / 2
for freq in map .values():
pair_with_num = freq * (freq - 1 ) / / 2
total_pair - = pair_with_num
return total_pair
def main():
N = 5
X = [ 3 , 4 , 4 , 5 , 1 ]
print (Max_SubArrays(N, X))
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void Main( string [] args)
{
int N = 5;
int [] X = { 3, 4, 4, 5, 1 };
Console.WriteLine(Max_SubArrays(N, X));
}
static long Max_SubArrays( int N, int [] X)
{
Dictionary< int , int > map = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (map.ContainsKey(X[i]))
map[X[i]]++;
else
map[X[i]] = 1;
}
long totalPair = N * (N - 1) / 2;
foreach (KeyValuePair< int , int > entry in map)
{
long freq = entry.Value;
long pairwithNum = freq * (freq - 1) / 2;
totalPair -= pairwithNum;
}
return totalPair;
}
}
|
Javascript
function maxSubArrays(N, X) {
const map = new Map();
for (let i = 0; i < N; i++) {
if (map.has(X[i])) {
map.set(X[i], map.get(X[i]) + 1);
} else {
map.set(X[i], 1);
}
}
let totalPair = (N * (N - 1)) / 2;
for (const [num, freq] of map) {
const pairWithNum = (freq * (freq - 1)) / 2;
totalPair -= pairWithNum;
}
return totalPair;
}
function main() {
const N = 5;
const X = [3, 4, 4, 5, 1];
console.log(maxSubArrays(N, X));
}
main();
|
Time Complexity: O(N)
Auxiliary Space: O(N), As HashMap is used to store frequencies.
Share your thoughts in the comments
Please Login to comment...