Kadane’s Algorithm

Problems: 

Given an array arr of N integers. Find the contiguous sub-array with maximum sum.

Example 1:

Input:

N = 5
arr[] = {1,2,3,-2,5}

Output:

9

Explanation:

Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which  is a contiguous subarray.

Example 2:

Input:

N = 4
arr[] = {-1,-2,-3,-4}

Output:

-1

Explanation:

Max subarray sum is -1  of element (-1)

Your Task:

You don’t need to read input or print anything. The task is to complete the function maxSubarraySum() which takes arr and N as input parameters and returns the sum of subarray with maximum sum.

Expected Time Complexity: O(N)

Expected Auxiliary Space: O(1)

Solution

Java Code:

import java.util.*;
import java.lang.*;
import java.io.*;

class CB {
	public static void main (String[] args) throws IOException{
		//code
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
int n =Integer.parseInt(br.readLine());
int[] a = new int[n];
String line = br.readLine();
String[] strs = line.trim().split("\\s+");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(strs[i]);
}
		    System.out.println(maxSum(a));
		}
		
	}
	static int maxSum(int a[])
	{
	    int max = Integer.MIN_VALUE , temp = 0;
	    for(int i=0 ; i<a.length ; i++)
	    {
	        temp+=a[i];
	        if(max<temp)max = temp;
	        if(temp<0)temp=0;
	    }
	    return max;
	}
}

C++ Code:

#include<bits/stdc++.h>
using namespace std;


 // } Driver Code Ends
class Solution{
    public:
    // arr: input array
    // n: size of array
    //Function to find the sum of contiguous subarray with maximum sum.
    int maxSubarraySum(int arr[], int n){
        
       int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < n; i++)
    {
        max_ending_here = max_ending_here + arr[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;

        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
        
    }
};

// { Driver Code Starts.

int main()
{
    int t,n;
    
    cin>>t; //input testcases
    while(t--) //while testcases exist
    {
        
        cin>>n; //input size of array
        
        int a[n];
        
        for(int i=0;i<n;i++)
            cin>>a[i]; //inputting elements of array
            
        Solution ob;
        
        cout << ob.maxSubarraySum(a, n) << endl;
    }
}
  // } Driver Code Ends

Leave a Comment

Your email address will not be published. Required fields are marked *