Largest Sum Contiguous Subarray - Kadane's Algorithm
PROBLEM :
Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.
Constraints:
1 = T = 40
1 = N = 100
-100 = A[i] <= 100
Example:
Input
2
3
1 2 3
4
-1 -2 -3 -4
Output
6
-1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include <iostream>
using namespace std;
int Kadanes_Algorithm(int [],int ) ;
int maxof(int ,int ) ;
int main() {
int t,arr[100],no,i ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
no=Kadanes_Algorithm(arr,no) ;
cout<<no<<endl ;
}
return 0;
}
int Kadanes_Algorithm(int arr[],int no)
{
int max ,curr ,i ;
max=arr[0] ;
curr=arr[0] ;
for(i=1;i<no;i++)
{
curr=maxof(arr[i],arr[i]+curr) ;
max=maxof(curr,max) ;
}
return max ;
}
int maxof(int a,int b)
{
return a>b?a:b ;
}
---------------------------------------------------------------------------------
Given an array containing both negative and positive integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.
Constraints:
1 = T = 40
1 = N = 100
-100 = A[i] <= 100
Example:
Input
2
3
1 2 3
4
-1 -2 -3 -4
Output
6
-1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include <iostream>
using namespace std;
int Kadanes_Algorithm(int [],int ) ;
int maxof(int ,int ) ;
int main() {
int t,arr[100],no,i ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>arr[i] ;
no=Kadanes_Algorithm(arr,no) ;
cout<<no<<endl ;
}
return 0;
}
int Kadanes_Algorithm(int arr[],int no)
{
int max ,curr ,i ;
max=arr[0] ;
curr=arr[0] ;
for(i=1;i<no;i++)
{
curr=maxof(arr[i],arr[i]+curr) ;
max=maxof(curr,max) ;
}
return max ;
}
int maxof(int a,int b)
{
return a>b?a:b ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment