write a program in java implement the brute force algorithm

write a program in java , implement the brute force algorithm  to find the maximum subarray.

Solution

Please follow the code and comments for description :

CODE :

public class maximumSubArray { // main class with the code implementation

    public static void main(String args[]) { // driver method
      
        int arrayData[] = {-1, 2, 4, 60, 1, -3, 2, -6, 7, -9, 1}; // random array data

        int maximumSum = 0; // required initialisations
        int maximumLower = 0;
        int maximumHigher = 0;
        int low = 0;
        int high = 0;
        int sum;
        int newSum;
        for (int i = 0; i < arrayData.length - 1; i++) { // iterating over the loop till the length of the array
            sum = 0;
            newSum = 0;
            sum = arrayData[i] + arrayData[i + 1]; // adding up the data and saving in the sum varaible
            newSum = sum; // shifting the value to the latest sum varaible
            low = i; // initialising the lower element
            high = i + 1; // initialising the higher element
            for (int j = i + 2; j < arrayData.length; j++) { // iterating over the loop from the second element to the end of array
                newSum = newSum + arrayData[j]; // getting the sum of the new array
                if (sum < newSum) { // checking for the new and old sum data
                    sum = newSum; // updating the sum value
                    high = j; // replacing the higher element
                }
            }
            if (sum > maximumSum) { // comparing the highest sum value
                maximumSum = sum; // shifting the value to the maximumsum value
                maximumHigher = high; // updating the higher and lower element values
                maximumLower = low;
            }
        }
        System.out.println(\"The Lower Bound Element is : \" + maximumLower); // printing the data
        System.out.println(\"The Higher Bound Element is : \" + maximumHigher);
        System.out.println(\"The Maximum Sum is : \" + maximumSum);
    }
}


OUTPUT :

The Lower Bound Element is : 1
The Higher Bound Element is : 4
The Maximum Sum is : 67

Hope this is helpful.

write a program in java , implement the brute force algorithm to find the maximum subarray.SolutionPlease follow the code and comments for description : CODE :

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site