Skip to content

Commit f4698d4

Browse files
authored
Create Split Array by Prime Indices.java
1 parent ba1f31c commit f4698d4

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public long splitArray(int[] nums) {
3+
Set<Integer> primeIndices = getPrimeIndices(nums.length);
4+
long primeSum = 0;
5+
long nonPrimeSum = 0;
6+
for (int i = 0; i < nums.length; i++) {
7+
if (primeIndices.contains(i)) {
8+
primeSum += nums[i];
9+
} else {
10+
nonPrimeSum += nums[i];
11+
}
12+
}
13+
return Math.abs(primeSum - nonPrimeSum);
14+
}
15+
16+
private Set<Integer> getPrimeIndices(int n) {
17+
boolean[] isPrime = new boolean[n + 1];
18+
for (int i = 2; i <= n; i++) {
19+
isPrime[i] = true;
20+
}
21+
for (int i = 2; i * i <= n; i++) {
22+
if (isPrime[i]) {
23+
for (int j = i * i; j <= n; j += i) {
24+
isPrime[j] = false;
25+
}
26+
}
27+
}
28+
Set<Integer> primeIndices = new HashSet<>();
29+
for (int i = 2; i <= n; i++) {
30+
if (isPrime[i]) {
31+
primeIndices.add(i);
32+
}
33+
}
34+
return primeIndices;
35+
}
36+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy