Search code examples
javaarraysnegative-number

How do I find the largest negative value in an array with both positive and negative values?


I need to return the greatest negative value, and if there are no negative values, I need to return zero. Here is what I have:

public int greatestNegative(int[] list) {


    for (int i = 0; i < list.length; i++) {


       if (list[i] < 0)
           negativeNumbers ++;
    }

    int j = list.length - 1;

    while (j >= 0) {
       if (list[j - negativeNumbers] < 0) {
        list[j] = 0;
        list[j - 1] = list[j - negativeNumbers];
        negativeNumbers--;
        j--;
       }
       else{
        list[j] = list[j - negativeNumbers];
        j--;
     }
  }

}

Solution

  • You just need to think of this problem as 2 steps:

    1. Only consider negative values in list[].
    2. In the loop within negative values, update current result if (result == 0) or (value > result).

    Code:

    public int greatestNegative(int[] list) {
        int result = 0;
        for (int i = 0; i < list.length; i++) {
            if (list[i] < 0) {
                if (result == 0 || list[i] > result) {
                    result = list[i];
                }
            }
        }
        return result;
    }