Maximum Subarray

Maximum Subarray Problem

Problem Description:

Given a sequence of n real numbers A(1) … A(n), determine a contiguous subsequence A(i) … A(j) for which the sum of elements in the subsequence is maximized.


Problem Solution:

We will proceed in a linear fashion maintaining overall_max and current_max variables. If adding the current element to current_max results in overall maximum value, we will replace the value of overall_max variable. Otherwise, we will proceed furthere.


Expected Input and Output:

Case-1:

A[]={2,4,6,8}

maximum contiguous subarry= {2, 4, 6, 8}

maximum contiguous subarray sum= 20


Case-2:

A[]={-2, 3, -7, 5, -9}

maximum contiguous subarry= {5}

maximum contiguous subarray sum= 5


Case-3:

A[]={3, -4, 7, -9, 8, 7}

maximum contiguous subarry= {8, 7}

maximum contiguous subarray sum= 15

 

A[]={3, -4, 9, -8, 8, 7}

maximum contiguous subarry= {9, -8, 8, 7}

maximum contiguous subarray sum= 16


Case-4:

A[]={3, -4, 9, -8, 8, 7}

maximum contiguous subarry= {9, -8, 8, 7}

maximum contiguous subarray sum= 16


Program/Source Code for Brute force solution:

Here is source code of the C++ Program to Solve Kadane’s Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.


#include<iostream>

using namespace std;

//This function will check every contiguous subarray and return the sum of maximum subarray

int maxSubarraySum(int a[], int n)

{

    int overall_sum=0;  //overall maximum subarray sum

    int new_sum;

    for(int i=0;i<n;i++)

    {

        //find the maximum subarray sum of the subarray starting from a[i]

        new_sum=0;

        for(int j=i;j<n;j++)

        {

            new_sum+=a[j];

            if(new_sum>overall_sum)

            {

                overall_sum=new_sum;

            }

        }

    }

    return overall_sum;

}

int main()

{

    int i,n;

    cout<<"Enter the number of elements in the array  ";

    cin>>n;

    int a[n];

    //read the vector

    cout<<"enter the elements in the array"<<endl;

    for(i=0;i<n;i++)

    {

        cin>>a[i];

    }

    //now,make a call to kadane function to calculate maximum subarray sum

    cout<<endl<<"The maximum subarray sum for the given array is "<<maxSubarraySum(a,n); 

    return 0;

}


Program/Source Code for Dynamic Programming solution:

Here is source code of the C++ Program to Solve Kadane’s Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.


#include<iostream>

using namespace std;

int kadane(int a[], int n)

{

    int overall_sum=0;  //overall maximum subarray sum

    int new_sum=0;      //sum obtained by including the current element

    for(int i=0;i<n;i++)

    {

        //new_sum is the maximum value out of current element or the sum of current element

        //and the previous sum

        new_sum=max(a[i], new_sum+a[i]);

        //if the calculated value of new_sum is greater than the overall sum,

        //it replaces the overall sum value

        overall_sum=max(overall_sum, new_sum);

    }

    return overall_sum;

}

 

int main()

{

    int i,n;

    cout<<"Enter the number of elements in the array  ";

    cin>>n;

    int a[n];

    //read the vector

    cout<<"enter the elements in the array"<<endl;

    for(i=0;i<n;i++)

    {

        cin>>a[i];

    }

    //now,make a call to kadane function to calculate maximum subarray sum

    cout<<endl<<"The maximum subarray sum for the given array is "<<kadane(a,n); 

    return 0;

}

Program Explanation:

In the main function, we ask the user to input the elements of the array. We pass this array to the function kadane as parameter. This function will calculate the expected result and return it. The returned value will be displayed.


Runtime Test Cases:

Case-1:

Enter the number of elements in the array 4

enter the elements in the array

2      

4

6

8

The maximum subarray sum for the given array is 20.



Let's see how implement the solution for this problem by using List predefined data type in java 😀:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

Explanation: [4,-1,2,1] has the largest sum = 6.


Example 2:

Input: nums = [1]

Output: 1


Example 3:

Input: nums = [0]

Output: 0


Example 4:

Input: nums = [-1]

Output: -1


Example 5:

Input: nums = [-2147483647]

Output: -2147483647

 


Constraints:

1 <= nums.length <= 2 * 104

-231 <= nums[i] <= 231 - 1


Program:

class Solution {

    public int maxSubArray(int[] nums) {

        // for(int i:nums){

        //     if ( ( (i>=(Math.pow(-2, 31)) ) && (i<= (Math.pow(2, 31) -1))) )

        //     {

        //         continue;

        //     }

        //     else

        //     {

        //         return 0;

        //     }

        // }

        List<Integer> list = new ArrayList<Integer>();

        Integer i, mx=nums[0];

        list.add(nums[0]);

        for(i=1;i<nums.length;i++)

        {

            Integer k =  nums[i]+list.get(i-1);

            list.add(Math.max(nums[i], k));

        }

        System.out.println(list);

        for(Integer j:list)

        {

            System.out.println(j + " " +  mx);

            if(j>mx)

            {

                mx = j;

            }

        }

        return mx;

    }


Execution:

Successfully Executed








Reference👉 Maximum Subarray || Kadane’s Algorithm – Dynamic Programming Solution


                                                                  Happy Coding 💻:-)


Comments

Popular posts from this blog

Valid Username Regular Expression

Rotate String in Right Direction in java

Java MCQ's