[LeetCode] Make Sum Divisible by P

1590. Make Sum Divisible by P

Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.

Return the length of the smallest subarray that you need to remove, or -1 if it’s impossible.

A subarray is defined as a contiguous block of elements in the array.

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
class Solution {
public:
int minSubarray(vector<int>& nums, int p) {
vector<long> sums(nums.size() + 1, 0);
unordered_map<int, int> index;

for(int i = 1; i < sums.size(); i++) {
sums[i] = sums[i - 1] + (nums[i - 1] % p);
}

int res = INT_MAX, back = sums.back() % p;

if(back == 0)
return 0;

for(int i = 0; i < sums.size(); i++) {
index[sums[i] % p] = i;
long remainder = (p + sums[i] - back) % p;
if(index.find(remainder) != index.end())
res = min(res, i - index[remainder]);
}

return res >= sums.size() ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/23/PS/LeetCode/make-sum-divisible-by-p/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.