Reputation: 13
I want to sum (running sum) the values of an int Array and put the result in new array on corresponding position. If sum <0, result should be 0. I'm trying to find a better way to write below code? Maybe with streams java8?
int[] originalArray = {3,7,-12,1,8,5};
int[] resultArray= new int[originalArray.length];
resultArray[0]=(originalArray[0]<0) ? 0:originalArray[0];
for(int i=1;i<originalArray.length;i++){
int sum=resultArray[i-1]+originalArray[i];
resultArray[i]=(sum<0) ? 0 : sum;
// System.out.println(resultArray[i]);
}
Upvotes: 0
Views: 346
Reputation: 19926
You don't need streams for this, a simple loop like you've already used is enough:
for (int i = 0, previous = 0; i < originalArray.length; i++) {
previous = resultArray[i] = Math.max(originalArray[i] + previous, 0);
}
You see that I introduced two things:
previous
: a helper variable, which tracks the previous resultMath.max()
: a useful method, it allows us to pick the result if it is positive or else 0
when it is negative (0
is greater than any negative)
The method looks something like this, which is exactly what you've done already:
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
If you don't like the multiple assignment line:
previous = resultArray[i] = Math.max(originalArray[i] + previous, 0);
Then you could also write it like this, if that's more understandable:
previous = Math.max(originalArray[i] + previous, 0);
resultArray[i] = previous;
Upvotes: 3