The challenge
Given an array of integers.
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array.
Example
For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]
, you should return [10, -65]
.
The solution in Java code
Option 1:
public class Solution {
public static int[] countPositivesSumNegatives(int[] input) {
if (input == null || input.length == 0) return new int[] {};
int count = 0, sum = 0;
for (int i : input) {
if (i > 0) count ++;
if (i < 0) sum += i;
}
return new int[] {count, sum};
}
}
Option 2:
import java.util.stream.*;
public class Solution {
public static int[] countPositivesSumNegatives(int[] input) {
return input == null || input.length == 0 ?
new int[0] :
new int[] { (int)IntStream.of(input).filter(i->i>0).count(), IntStream.of(input).filter(i->i<0).sum() };
}
}
Option 3:
import java.util.Arrays;
public class Solution {
public static int[] countPositivesSumNegatives(int[] input) {
if(input == null || input.length == 0) return new int[0];
int[] result = new int[2];
result[0] = (int) Arrays.stream(input).filter(i -> i > 0).count();
result[1] = Arrays.stream(input).filter(i -> i < 0).sum();
return result;
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runners.JUnit4;
public class SolutionTests {
@Test
public void countPositivesSumNegatives_BasicTest() {
int[] expectedResult = new int[] {10, -65};
assertArrayEquals(expectedResult, Solution.countPositivesSumNegatives(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15}));
}
@Test
public void countPositivesSumNegatives_InputWithZeroes() {
int[] expectedResult = new int[] {8, -50};
assertArrayEquals(expectedResult, Solution.countPositivesSumNegatives(new int[] {0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14}));
}
}