Question

In: Computer Science

Scenario Create an algorithm to solve the maximum subarray problem. Find the non-empty, contiguous subarray of...

Scenario
Create an algorithm to solve the maximum subarray problem. Find the non-empty, contiguous subarray of the input array whose values have the largest sum. You can see an example array with the maximum subarray indicated in the following diagram:

Screen Shot 2019-01-07 at 10.58.06 AM.png
The O(n2) brute force algorithm that tests all combinations for the start and end indices of the subarray is trivial to implement. Try to solve this using the divide and conquer algorithm.

Aim
To design and implement an algorithm to solve the maximum subarray problem with a better runtime than the O(n2) brute force algorithm, using a divide and conquer approach.

Prerequisites
You need to implement the maxSubarray() method of the MaximumSubarray class in the source code, which returns the sum of values for the maximum subarray of the input array. Assume that the sum always fits in an int, and that the size of the input array is at most 100,000.

public class MaximumSubarray {
public Integer maxSubarray(int[] a) {
return null;
}
}
The divide and conquer approach suggests that we divide the subarray into two subarrays of as equal size as possible. After doing so, we know that a maximum subarray must lie in exactly one of following three places:

Entirely in the left subarray
Entirely in the right subarray
Crossing the midpoint
Steps for Completion
The maximum subarray of the arrays on the left and right is given recursively, since those subproblems are smaller instances of the original problem.
Find a maximum subarray that crosses the midpoint.

Solutions

Expert Solution

I have attached the code for finding the maximum subarray sum using Divide and Conquer technique. Tha complexity of the code is O(nlog(n)). In the program, I have commented out the working of the algorithm. If you have any doubt, feel free to ask me.

MaximumSubarray.java:

import java.util.*;

public class MaximumSubarray{

    /*This function finds the max sum of subarray that
    crosses the middle element*/
    private Integer maxCrossingSum(int arr[], int left, int middle, int right)
    {
        //now we calculate maximum continuous sum in left part
        int sum = 0;
        int max_left_sum = arr[middle];
        for (int i = middle; i >= left; i--)
        {
            sum = sum + arr[i];
            if (sum > max_left_sum)
                max_left_sum = sum;
        }

        //now we calculate maximum continuous sum in right part
        sum = 0;
        int max_right_sum = arr[middle+1];
        for (int i = middle + 1; i <= right; i++)
        {
            sum = sum + arr[i];
            if (sum > max_right_sum)
            max_right_sum = sum;
        }
        //Now we need to return the sum of both maximum of left and max of right
        return max_left_sum + max_right_sum;
    }
  
    //this is helper function which performs recursion
    private Integer maxSubarrayHelper(int[] arr , int left , int right){
        //check if left == right , then there is single element , return
        if(left == right){
            return arr[left];
        }
        //get index of middle element
        int middle = (left + right) / 2;
        /*now we have three situation
        1) The max subarray lies completely in left half subarray
        2) The max subarray lies completely in right half subarray
        3) The max subarray contains elements of both right and left half subarray and crosses mid
        //Therefore we calculate each and return the maximum of three
        */
        return Math.max(Math.max(maxSubarrayHelper(arr, left, middle),//left half subarray,
                        maxSubarrayHelper(arr, middle + 1, right)),//right half subarray
                        maxCrossingSum(arr, left, middle, right)/*maximum crossing sum*/);
      
    }

    public Integer maxSubsrray(int arr[])
    {
        //call helper function
        return maxSubarrayHelper(arr , 0 , arr.length - 1);
    }

    //driver methods to test the code
    public MaximumSubarray(){

    }
    public static void main(String[] args){
        int[] arr = {-1 , -3, 4 , 5, -2, 4, 5, 7,-10 };
        System.out.println("Max Subarray Sum: " + new MaximumSubarray().maxSubsrray(arr));
    }
}

Code Screenshots:

Sample output for array: {-1 , -3, 4 , 5, -2, 4, 5, 7,-10 }


Related Solutions

Solve the linear programming problem by the method of corners. Find the minimum and maximum of...
Solve the linear programming problem by the method of corners. Find the minimum and maximum of P = 4x + 2y subject to 3x + 5y ≥ 20 3x + y ≤ 16 −2x + y ≤ 1 x ≥ 0, y ≥ 0. The minimum is P =   at (x, y) = The maximum is P =   at (x, y) =
create a genetic algorithm for knapsack problem in c++
create a genetic algorithm for knapsack problem in c++
Recall the activity selection problem where you find the maximum subset of non-overlapping activities by selecting...
Recall the activity selection problem where you find the maximum subset of non-overlapping activities by selecting the activities in increasing order of their finish time. Suppose that instead of always selecting the first activity to finish, we instead select the last activity to start that is compatible with all previously selected activities. You think this will always yield an optimal solution for activity selection problem? If no give a counter example. Otherwise give correctness proof.
You'll implement a completely generic version of an algorithm to find the maximum of an array....
You'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface. Create a public class named Max with a single class method named max. max should accept an array of Objects that implement Comparable and return the maximum. If the array is...
write a recursive algorithm to find the maximum element in an array of n elements and...
write a recursive algorithm to find the maximum element in an array of n elements and analyze its time efficiency. (I am using c++ programming language)
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm...
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm being used) Requirements Choose one problem with an algorithm and implement it. You should show and explain the result whatever you got. I recommend using N-Queen problem (at least N=8 or more) or any simple perfect games. For example, - N-Queen problem with hill climbing - N-Queen problem with simulated annealing - N-Queen problem with genetic algorithm - Tic-Tac-Toe with Minimax
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm...
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm being used) N-Queen problem with genetic algorithm Please use the N-Queen problem (at least N=8 or more) or any simple perfect games. Please provide a screenshot of output and please heavily comment the code. Thanks!
Solve the LP problem. If no optimal solution exists, indicate whether the feasible region is empty...
Solve the LP problem. If no optimal solution exists, indicate whether the feasible region is empty or the objective function is unbounded. HINT [See Example 1.] (Enter EMPTY if the region is empty. Enter UNBOUNDED if the function is unbounded.) Minimize c = 0.2x + 0.3y subject to 0.2x + 0.1y ≥ 1 0.15x + 0.3y ≥ 1.5 10x + 10y ≥ 80 x ≥ 0, y ≥ 0. c = (x, y) =
Objectives: Learn to analyze a computational problem and construct an algorithm to solve it Learn to...
Objectives: Learn to analyze a computational problem and construct an algorithm to solve it Learn to use sequential statements to build a basic program to implement the algorithm, using correct programming format Learn to use the scanf function to read and store values entered on the keyboard by the user, and the printf function used to display output results on the computer monitor Learn to convert math formulas into correct arithmetic expressions using variables, constants, and library math functions Learn...
Part1: 1.An algorithm is . a) a series of actions that solve a particular problem. b)...
Part1: 1.An algorithm is . a) a series of actions that solve a particular problem. b) an english description of a problem to be solved. c) the process of converting between data types. d) None of the above. 2. Program control is best defined as . a) the degree of control a program has over the computer on which it is executed. b) the line of code that is executing at a given time. c) the order in which a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT