-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubarray.cpp
70 lines (53 loc) · 1.59 KB
/
subarray.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
// summary for subarray & subsequence
subarray: a continuous segment of the array
subsequence: a subset of the array with the fixed order
// subsarray problem and methods
//
// 1. moving window of a fixed width k:
// - add a new element, delete the oldest element (update local/global)
// - deque (push_back(), pop_front())
// 2. two pointers (moving window of varying length)
int r = 0;
for (int l = 0; l < data.size(); ++l) {
while (r < n) {
if ( ) { // if not satisfied
// update state at r
++r;
} else {
break;
}
}
// update state at l
}
// 3. preSum / preProd
// subSum = preSum[j] - preSum[i]; // i, ..., j-1
vector<int> preSum(n + 1, 0);
for (int i = 1; i <= n; ++i) {
preSum[i] += preSum[i - 1] + data[i - 1]; // preSum[i]: 0, 1, ..., i-1
}
unordered_set<int> saved;
for (int i = 0; i <= n; ++i) {
if (saved.count(preSum[i] - target)) return true;
saved.insert(preSum[i]);
}
return false;
// postSum
vector<int> postSum(n+1, 0);
for (int i = n-1; i >= 0; --i) {
postsum[i] = postsum[i+1] + nums[i]; // postSum[i]: i, ..., n-1
}
// for (int i = 1; i <= n; ++i) {
// postSum[i] = postSum[i-1] + data[n-i]; // postSum[i]: n-i, n-i+1, ..., n-1
// }
// 4. DP
// dp[i]: XXX of the first i elements
// dp[i]: XXX ending in the i-th element
// dp[i][j]: XXX of subarray from index i to j
// is array A a subsequence of array B
bool isSubsequence(vector<int> &A, vector<int> &B) {
int i = 0;
for (int j = 0; j < B.size(); ++j) {
if (A[i] == B[j]) ++i;
}
return (i == A.size());
}