Java > Array-2 > zeroMax (CodingBat Solution)

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}


Solution:

public int[] zeroMax(int[] nums) {
  int max = 0;
  
  for (int i = nums.length-1; i >= 0; i--) {
    if (nums[i] % 2 != 0)
      max = Math.max(max, nums[i]);
    if (nums[i] == 0)
          nums[i] = max;
  }
  return nums;
}


4 comments :

  1. Yeah, it's smart! How about go through form the beginning? I know, not good as that one :-|
    public int[] zeroMax(int[] nums) {
    int max=0;
    for (int i=0; i<nums.length; i++) {
    if (nums[i]==0) {
    for (int j=i+1; j<nums.length; j++) {
    if (nums[j]%2==1) {

    max = Math.max(max,nums[j]);
    }
    }
    nums[i]=max;
    //need reset max here.
    max=0;
    }

    }
    return nums;
    }

    ReplyDelete
    Replies
    1. Basically looping the array beginning from the previous 0. Nice one

      Delete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact