forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-size-subarray-in-infinite-array.cpp
58 lines (53 loc) · 1.75 KB
/
minimum-size-subarray-in-infinite-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
// Time: O(n)
// Space: O(1)
// two pointers, sliding window
class Solution {
public:
int minSizeSubarray(vector<int>& nums, int target) {
static const int INF = numeric_limits<int>::max();
const int64_t total = accumulate(cbegin(nums), cend(nums), 0ll);
const int64_t q = target / total;
target %= total;
if (!target) {
return q * size(nums);
}
int result = INF;
int curr = 0;
for (int right = 0, left = 0; right < (size(nums) - 1) + (size(nums) - 1); ++right) {
curr += nums[right % size(nums)];
while (curr > target) {
curr -= nums[left++ % size(nums)];
}
if (curr == target) {
result = min(result, right - left + 1);
}
}
return result != INF ? result + q * size(nums) : -1;
}
};
// Time: O(n)
// Space: O(n)
// prefix sum, hash table
class Solution2 {
public:
int minSizeSubarray(vector<int>& nums, int target) {
static const int INF = numeric_limits<int>::max();
const int64_t total = accumulate(cbegin(nums), cend(nums), 0ll);
const int64_t q = target / total;
target %= total;
if (!target) {
return q * size(nums);
}
int result = INF;
unordered_map<int64_t, int> lookup = {{0, -1}};
int64_t prefix = 0;
for (int right = 0; right < (size(nums) - 1) + (size(nums) - 1); ++right) {
prefix += nums[right % size(nums)];
if (lookup.count(prefix - target)) {
result = min(result, right - lookup[prefix - target]);
}
lookup[prefix] = right;
}
return result != INF ? result + q * size(nums) : -1;
}
};