Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create 1590. Make Sum Divisible by P #603

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions 1590. Make Sum Divisible by P
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
typedef long long ll;
class Solution {
public:
int minSubarray(vector<int>& nums, int p) {
/*
3 1 4 2 totalsum=10
remove 3 or 31 or 314
remove 1 or 14 or 142
remove 4 or 42
remove 2
0 3 1 4 2
ps[0 3 4 8 10]
brute force O(N*2);
how to do it nlogn or n
if on subtracting from sum a number which has same remainder when%p
thats the ans
now question becomes finding subarrya with sum as sum%p
*/
int n=nums.size();
ll totalsum=0;
for(auto& i:nums)totalsum+=i;
if(totalsum%p==0)return 0;
ll rem=totalsum%p;
unordered_map<ll,int>mp;
ll sum=0;int ans=n;
mp[0]=-1;
for(int i=0;i<n;i++){
sum = (sum+nums[i])%p;
ll remsum=(sum-rem+p)%p;
if(mp.find(remsum)!=mp.end())ans=min(ans,i-mp[remsum]);
mp[sum]=i;
}
if(ans==n)return -1;
return ans;
}
};
Loading