-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefix_sum_ArrayRanges.cpp
More file actions
48 lines (42 loc) · 979 Bytes
/
Prefix_sum_ArrayRanges.cpp
File metadata and controls
48 lines (42 loc) · 979 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// C++ program to find maximum occured element in
// given N ranges.
#include <bits/stdc++.h>
#define MAX 1000000
using namespace std;
// Return the maximum occurred element in all ranges.
int maximumOccuredElement(int L[], int R[], int n)
{
// Initalising all element of array to 0.
int arr[MAX];
memset(arr, 0, sizeof arr);
// Adding +1 at Li index and substracting 1
// at Ri index.
int maxi=-1;
for (int i = 0; i < n; i++) {
arr[L[i]] += 1;
arr[R[i] + 1] -= 1;
if(R[i]>maxi){
maxi=R[i];
}
}
// Finding prefix sum and index having maximum
// prefix sum.
int msum = arr[0],ind;
for (int i = 1; i < maxi+1; i++) {
arr[i] += arr[i - 1];
if (msum < arr[i]) {
msum = arr[i];
ind = i;
}
}
return ind;
}
// Driven Program
int main()
{
int L[] = { 1, 4, 9, 13, 21 };
int R[] = { 15, 8, 12, 20, 30 };
int n = sizeof(L) / sizeof(L[0]);
cout << maximumOccuredElement(L, R, n) << endl;
return 0;
}