Skip to content

Commit a5bfa70

Browse files
authored
Create 1590. Make Sum Divisible by P 1 (#945)
2 parents c8b8fca + 4e27b94 commit a5bfa70

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

1590. Make Sum Divisible by P 1

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)