Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array-2 zeromax codingbat

Tags:

java

arrays

I'm trying to solve this array problem on codingbat but i have some problems the problem with my code is it does not find the largest odd number

the assignment is 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.

[0, 5, 0, 3]) --- [5, 5, 3, 3] | [0, 4, 0, 3])  ---[3, 4, 3, 3] | [0, 1, 0])  --- [1, 1, 0]

here is my code

public int[] zeroMax(int[] nums) {
    int max =0 , val = nums.length;
    for (int i = 0; i < nums.length-1; i++){
     if (nums[val-1] % 2 != 0 && nums[val-2] == 0){
      max = Math.max(max, nums[val-1]);
      nums[val-2] = max;
     }else if (nums[val-1] % 2 ==0 && nums[val-2] == 0)
       nums[val-2] = max;
     val--;
    }
    return nums;
  }
like image 338
john mac Avatar asked Feb 25 '26 18:02

john mac


1 Answers

You're on the right track, but your code seems a little complex.

To solve the problem at hand you'll need a nested loop, the outer loop to iterate over the elements within the array and if the number at the current index is 0 then we will need to start another loop to search to the right of the array to find the largest odd number and if found we replace the element 0 at the current index with the odd number; else we leave it as is.

Example:

for (int i = 0; i < nums.length-1; i++){
      if(nums[i] == 0){ // if current element is 0
           int largestOddNumber = Integer.MIN_VALUE; // temp largest odd number
           boolean oddNumberExists = false; // is there an odd number to the right of the 0
           for (int j = i + 1; j < nums.length; j++){
               if(nums[j] % 2 != 0){ // is it an odd number
                  largestOddNumber = Math.max(largestOddNumber, nums[j]); // get largest odd number
                   oddNumberExists = true; // there exists an odd number
               }
           }
           if (oddNumberExists) nums[i] = largestOddNumber; // if odd number exists then replace 0 with the largest odd number
      }
}
return nums; //return modified array;
like image 163
Ousmane D. Avatar answered Feb 28 '26 07:02

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!