File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments