File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int minSubarray(vector<int>& nums, int p) {
4+ long long sufsum = 0;
5+ for (auto x : nums) {
6+ sufsum += x;
7+ }
8+
9+ long long presum = 0;
10+ int n = nums.size();
11+ int ans = n;
12+ unordered_map<int, int> dp;
13+
14+ // "Virtual" prefix: sum 0 at index -1 (empty prefix)
15+ dp[0] = -1;
16+
17+ for (int i = 0; i < n; i++) {
18+ presum += nums[i]; // extend prefix
19+ sufsum -= nums[i]; // shrink suffix
20+
21+ // Store the latest index with this prefix remainder
22+ dp[presum % p] = i;
23+
24+ // Right remainder and required left remainder
25+ int rem = (p - sufsum % p) % p;
26+
27+ // If we have some prefix with this remainder,
28+ // try removing between it and i
29+ if (dp.find(rem) != dp.end()) {
30+ ans = min(ans, i - dp[rem]);
31+ }
32+ }
33+
34+ if (ans == n) return -1;
35+ return ans;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments