File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ typedef long long ll;
2+ class Solution {
3+ public:
4+ int minSubarray(vector<int>& nums, int p) {
5+ /*
6+ 3 1 4 2 totalsum=10
7+ remove 3 or 31 or 314
8+ remove 1 or 14 or 142
9+ remove 4 or 42
10+ remove 2
11+ 0 3 1 4 2
12+ ps[0 3 4 8 10]
13+ brute force O(N*2);
14+ how to do it nlogn or n
15+ if on subtracting from sum a number which has same remainder when%p
16+ thats the ans
17+ now question becomes finding subarrya with sum as sum%p
18+ */
19+ int n=nums.size();
20+ ll totalsum=0;
21+ for(auto& i:nums)totalsum+=i;
22+ if(totalsum%p==0)return 0;
23+ ll rem=totalsum%p;
24+ unordered_map<ll,int>mp;
25+ ll sum=0;int ans=n;
26+ mp[0]=-1;
27+ for(int i=0;i<n;i++){
28+ sum = (sum+nums[i])%p;
29+ ll remsum=(sum-rem+p)%p;
30+ if(mp.find(remsum)!=mp.end())ans=min(ans,i-mp[remsum]);
31+ mp[sum]=i;
32+ }
33+ if(ans==n)return -1;
34+ return ans;
35+ }
36+ };
You can’t perform that action at this time.
0 commit comments