-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily108.cpp
More file actions
90 lines (74 loc) · 2.48 KB
/
Copy pathdaily108.cpp
File metadata and controls
90 lines (74 loc) · 2.48 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Solution 1 - FAIL
class Solution {
public:
int minSubarray(vector<int>& nums, int p) {
/*
brute force:
at least n^2
remove element by element, then two element by two element, then three ...
until you find the smallest subarray
return such subarray
recursive backtracking solution:
try removing one element
if removed element makes sum less than p, try another element
if r.e makes sum greater than p, recurse without that element in next stage
if equal, return amount of removed elements
INCORRECT
sliding window
*/
p_ = p;
nums_ = nums;
size_ = nums.size();
auto sum = std::accumulate(nums.begin(), nums.end(), 0);
bt(sum);
return min_sub_;
}
private:
void bt(int curr_sum) {
std::cout << "curr sum is " << curr_sum << ", with " << nums_.size() << " numbers in the array" << std::endl;
if (curr_sum <= 0 or nums_.size() == 1)
return;
if (curr_sum % p_ == 0) {
if (nums_.size() == size_)
min_sub_ = 0;
else
min_sub_ = std::min(min_sub_, static_cast<int>(size_ - nums_.size()));
return;
}
for (auto n = nums_.begin(); n != nums_.end();) {
auto value = *n;
auto remainder = curr_sum - value;
n = nums_.erase(n);
bt(remainder);
nums_.push_back(value);
}
}
int p_;
int size_;
std::vector<int> nums_;
int min_sub_ = -1;
};
// Solution 2
class Solution {
public:
int minSubarray(vector<int>& nums, int p) {
long long sum = 0;
for (int num : nums) sum += num;
int target = sum % p;
if (target == 0) return 0;
unordered_map<int, int> last_occurrence;
last_occurrence[0] = -1;
int min_length = nums.size();
long long current_sum = 0;
for (int i = 0; i < nums.size(); i++) {
current_sum += nums[i];
int remainder = current_sum % p;
int complement = (remainder - target + p) % p;
if (last_occurrence.count(complement)) {
min_length = min(min_length, i - last_occurrence[complement]);
}
last_occurrence[remainder] = i;
}
return min_length < nums.size() ? min_length : -1;
}
};