forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_1524.java
46 lines (44 loc) · 1.34 KB
/
_1524.java
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
package com.fishercoder.solutions;
public class _1524 {
public static class Solution1 {
/**
* This brute force solution will throw exceed time limit exceeded exception on LeetCode.
*/
public int numOfSubarrays(int[] arr) {
long oddCount = 0;
for (int i = 0; i < arr.length; i++) {
long subTotal = 0;
for (int j = i; j < arr.length; j++) {
subTotal += arr[j];
if (subTotal % 2 != 0) {
oddCount++;
}
}
}
return (int) oddCount % 1000000007;
}
}
public static class Solution2 {
public int numOfSubarrays(int[] arr) {
int oddSumCount = 0;
int evenSumCount = 1;
long result = 0;
int sum = 0;
for (int num : arr) {
sum += num;
if (sum % 2 == 0) {
result += oddSumCount;
} else {
result += evenSumCount;
}
if (sum % 2 == 0) {
evenSumCount++;
} else {
oddSumCount++;
}
result %= 1000000007;
}
return (int) result % 1000000007;
}
}
}