* Here we just iterate through the given interval and do a brute-force maximum/minimum search.
* Time complexity is O(N).
* We examine all possible solutions and hence it can be very slow BUT is guaranteed to find the optimal solution.

Codes of the Java files included in the program are given below:

BruteForceSearch.java

In [ ]:
package bruteforcesearch;
/**
 *
 * @author ANIRUDDHA
 */
public class BruteForceSearch {

    // The function whose max/min is to be found
    public static double func(double x){
        return -(x*x)+2;
    }
    
    public static void main(String[] args) {
    
        double startPositionX = -2;
        double maximumX = startPositionX;
        double dx = 0.01; //Intervals
        double max = func(startPositionX);
        
        // Iterate through the whole function 
		// and then decide the global max
        for (double i = startPositionX; i<2; i+= dx){
            if(func(i) > max ){
                max= func(i);
                maximumX = i;
            }
        }
        
        System.out.println("The maximum is at x= "+ maximumX + "and y= "+ func(maximumX));
        
    }
    
}

Output of the program is :

The maximum is at x= 1.6410484082740595E-15and y= 2.0

You can download the complete source code here : Source Code