Find Element Before Which All Elements Are Smaller Than It, And After Which All Are Greater

plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}
package org.wesome.dsalgo;

import java.util.Arrays;

public class MiddleElement {
    static int findElement(int[] arr) {
        int[] maxFromLeft = new int[arr.length];
        maxFromLeft[0] = Integer.MIN_VALUE;
        /*  Fill the maxFromLeft array with maximum of current with previous minimum    */
        for (int i = 1; i < arr.length; i++) {
            maxFromLeft[i] = Math.max(maxFromLeft[i - 1], arr[i - 1]);
        }
        System.out.println("left Max Array " + Arrays.toString(maxFromLeft));
        int rightMin = Integer.MAX_VALUE;
        int result = -1;
        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.println("left Max " + maxFromLeft[i] + " current element " + arr[i] + " rightMin " + rightMin);
            /*  if current element is greater then maxFromLeft ar*/
            if (maxFromLeft[i] < arr[i] && arr[i] < rightMin) {
                System.out.println("element is = " + arr[i]);
                result = arr[i];
            }
            rightMin = Math.min(rightMin, arr[i]);
        }
        return result;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class MiddleElementTest {
    @Test
    void middleElementTest1() {
        int[] arr = {5, 1, 4, 3, 6, 8, 10, 7, 9};
        Assertions.assertEquals(6, MiddleElement.findElement(arr));
    }
}

 

follow us on