forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_Lookup_in_1D_array.cpp
67 lines (55 loc) · 1.66 KB
/
Reverse_Lookup_in_1D_array.cpp
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Problem :
Given an array of size N. Find the total sum of all the subarrays in the array.
-->Efficient Method : (USING REVERSE LOOKUP)
-> Find the count of subarrays where a particular element is included.
-> Once we have the repetition number, we can multiply it with the value of element to get its contribution.
-> For an element with value 'X' at i-th position :-
-- the number of subarrays starting from index 0 to i = i + 1
-- the number of subarrays ending on indices from i to N-1 = N - i
-> The total contribution by X = X * repetitions = X * ((i + 1) * (N - i)).
-> Total time complexity => O(N).
Note :-
Modular arithmethic to avoid overflows:
-> (a + b) % M = ((a % M) + (b % M)) % M
-> (a * b) % M = ((a % M) * (b % M)) % M
where, M = 10^9 + 7
*/
#include <bits/stdc++.h>
using namespace std;
const long long M = 1e9 + 7;
/* function subset_sums() calculates the total sum of all subsets.
contribution variable denotes the contribution given by each element in the array.
*/
long long subset_sums(vector<int>& array, int n){
long long sum = 0, contribution;
for (int i = 0; i < n; i++) {
contribution = (((i+1) % M * (n-i) % M) % M * array[i] % M) % M;
sum = ((sum % M) + (contribution % M)) % M;
}
return sum;
}
int main()
{
int n, value;
long long total_sum;
vector<int> array;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> value;
array.push_back(value);
}
// calculating subset sums
total_sum = subset_sums(array, n);
cout << total_sum << endl;
return 0;
}
/*
Input :
6
2 3 4 7 8 9
Output:
308
Time Complexity : O(n)
Space Complexity : O(1)
*/