-
Notifications
You must be signed in to change notification settings - Fork 5
/
WaysToMakeAFairArray.java
47 lines (42 loc) · 1.39 KB
/
WaysToMakeAFairArray.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
47
/*https://leetcode.com/problems/ways-to-make-a-fair-array/*/
class Solution {
public int waysToMakeFair(int[] nums) {
int leftOdd = 0, rightOdd = 0, leftEven = 0, rightEven = 0, i, j, n = nums.length, count = 0;
boolean turn = true;
for (i = 0; i < n; ++i)
{
if (turn) rightOdd += nums[i];
else rightEven += nums[i];
turn = !turn;
}
i = 0;
turn = true;
while (i < n)
{
if (turn) rightOdd -= nums[i];
else rightEven -= nums[i];
if (rightOdd+leftEven == leftOdd+rightEven) ++count;
if (turn) leftOdd += nums[i];
else leftEven += nums[i];
turn = !turn;
++i;
}
return count;
}
}
class Solution {
public int waysToMakeFair(int[] nums) {
int leftOdd = 0, rightOdd = 0, leftEven = 0, rightEven = 0, i, j, n = nums.length, count = 0;
for (i = 0; i < n; ++i)
if ((i&1) == 0) rightOdd += nums[i]; else rightEven += nums[i];
i = 0;
while (i < n)
{
if ((i&1) == 0) rightOdd -= nums[i]; else rightEven -= nums[i];
if (rightOdd+leftEven == leftOdd+rightEven) ++count;
if ((i&1) == 0) leftOdd += nums[i]; else leftEven += nums[i];
++i;
}
return count;
}
}