Home > Back-end >  Delete local maximum
Delete local maximum

Time:06-08

A local maximum is an element that is greater than any of its neighboring elements. You must remove elements that are local maxima in the original array.

Input array: [18, 1, 3, 6, 7, -5]

output array: [1, 3, 6, -5]

public static int[] removeLocalMaxima(int[] array){
        int[] result = new int[array.length];
        int j = 0;
 
        for (int i = 0; i < array.length - 1; i  , j  ) {
            if(array[i] > array[i   1]){
                result[j] = array[  i];
            }else {
                result[j] = array[i];
            }
        }
        return  Arrays.copyOf(result, j);
    }

if you set it like that, then something is not working:

array = new int[1000];
            Arrays.fill(array, 15);
            array[0] = -20;
            array[999] = 25;
            array[168] = 18;
            array[421] = 0;
            actual = LocalMaximaRemove.removeLocalMaxima(array);
 
            assertEquals(998, actual.length);
            assertEquals(-20, actual[0]);
            assertEquals(15, actual[997]);
            assertEquals(0, actual[420]);

CodePudding user response:

public static int[] removeLocalMaxima(int[] array){
    int[] result = new int[array.length];
    int j = 0;

    for (int i = 0; i < array.length; i  ) {
        if ((i > 0 && array[i] <= array[i - 1])
                || (i != array.length - 1 && array[i] <= array[i   1])){
            result[j  ] = array[i];
        }
    }
    return Arrays.copyOf(result, j);
}

My function saves in result array only elements that are less or equal of any of its neightbors.

  •  Tags:  
  • java
  • Related