Alejandro Cordoba Bodhert - 3 months ago 9
Java Question

# Java > Array-2 > zeroMax

my code only misses 5 cases and i dont know why, somebody help me.

problem

Return a version of the given array where each zero value in the array
is replaced by the largest odd value to the right of the zero in the
array. If there is no odd value to the right of the zero, leave the
zero as a zero.

zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}

zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}

zeroMax({0, 1, 0}) → {1, 1, 0}

my code

``````public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for( i = 0; i < nums.length;i++){
if(nums[i]==0){
for(int j = i; j < nums.length;j++){
if (nums[j]%2!=0){
acum = nums[j];
break;
}
}
nums[i]=acum;
}

}
return nums;
}
``````

What you are missing is, that there could be more than one odd number on the right side of your zero and you need to pick the largest one.

Edit: And you also need to reset 'acum'. I updated my suggestion :)

Here's a suggestion:

``````public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > acum) {
acum = nums[j];
}
}
nums[i] = acum;
acum = 0;
}

}
return nums;
}
``````
Source (Stackoverflow)