-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
51 lines (46 loc) · 1.2 KB
/
main.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
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int ans = 0;
for (int length = 1; length <= size(arr); length += 2) {
for (int i = 0; i <= size(arr) - length; ++i) {
for (int j = i; j < i + length; ++j) {
ans += arr[j];
}
}
}
return ans;
}
};
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int result = 0;
int n = arr.size();
for (int i = 0; i < n; ++i) {
int l = i + 1;
int r = n - i;
result += arr[i] * ((l * r + 1) / 2);
}
return result;
}
};
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int n = arr.size();
vector<int> prefix_sum(n);
for (int i = 0, sum = 0; i < n; ++i) {
prefix_sum[i] = sum += arr[i];
}
int result = 0;
for (int l = 0; l < n; ++l) {
for (int r = l; r < n; r += 2) {
int s = prefix_sum[r];
if (l > 0) s -= prefix_sum[l - 1];
result += s;
}
}
return result;
}
};