-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_26.java
More file actions
48 lines (44 loc) · 1.21 KB
/
Copy pathDay_26.java
File metadata and controls
48 lines (44 loc) · 1.21 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Maximum Subarray
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int maxi = Integer.MIN_VALUE, sum = 0;
for(int i=0;i<n;i++){
sum+=nums[i];
maxi = Math.max(maxi,sum);
if(sum<0) sum = 0;
}
return maxi;
}
}
// Contains Duplicate II
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int n = nums.length;
HashMap<Integer,Integer> mpp = new HashMap<>();
for(int i=0;i<n;i++){
if(mpp.containsKey(nums[i])){
int val = mpp.get(nums[i]);
if(Math.abs(val-i) <= k) return true;
}
mpp.put(nums[i],i);
}
return false;
}
}
// Subarray Sum Equals K
class Solution {
public int subarraySum(int[] nums, int k) {
int n = nums.length;
int cnt = 0, presum = 0;
HashMap<Integer,Integer> mpp = new HashMap<>();
mpp.put(0,1);
for(int i=0;i<n;i++){
presum+=nums[i];
int remove = presum - k;
cnt+=mpp.getOrDefault(remove,0);
mpp.put(presum,mpp.getOrDefault(presum,0) + 1);
}
return cnt;
}
}