Skip to content

Commit 47efe15

Browse files
authored
Resolved 3729 Problem in Java
1 parent 375d1d2 commit 47efe15

File tree

1 file changed

+49
-1
lines changed
  • solution/3700-3799/3729.Count Distinct Subarrays Divisible by K in Sorted Array

1 file changed

+49
-1
lines changed

solution/3700-3799/3729.Count Distinct Subarrays Divisible by K in Sorted Array/README_EN.md

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,55 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/3700-3799/3729.Co
7878
#### Java
7979

8080
```java
81-
81+
class Solution {
82+
public long numGoodSubarrays(int[] nums, int k) {
83+
long A = 0;
84+
Map<Integer, Integer> modMap = new HashMap<>();
85+
modMap.put(0, 1);
86+
long prefix = 0;
87+
88+
// First part: prefix sums mod k
89+
for (int v : nums) {
90+
prefix = (prefix + v) % k;
91+
if (prefix < 0) prefix += k;
92+
int mod = (int) prefix;
93+
A += modMap.getOrDefault(mod, 0);
94+
modMap.merge(mod, 1, Integer::sum);
95+
}
96+
97+
// Second part: handle consecutive identical segments efficiently
98+
long C = 0, B = 0;
99+
int i = 0;
100+
while (i < nums.length) {
101+
int j = i;
102+
while (j < nums.length && nums[j] == nums[i]) j++;
103+
104+
int segLen = j - i;
105+
long v = nums[i];
106+
long g = gcd(Math.abs(v), k);
107+
long step = k / g;
108+
109+
long countL = segLen / step; // number of valid L values
110+
if (countL > 0) {
111+
// Sum of contributions for all valid L
112+
C += countL * (segLen + 1) - step * countL * (countL + 1) / 2;
113+
B += countL;
114+
}
115+
i = j;
116+
}
117+
118+
return A - C + B;
119+
}
120+
121+
private long gcd(long a, long b) {
122+
while (b != 0) {
123+
long temp = a % b;
124+
a = b;
125+
b = temp;
126+
}
127+
return a;
128+
}
129+
}
82130
```
83131

84132
#### C++

0 commit comments

Comments
 (0)