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 maxof(int a,int b){
    return a>b?a:b ;
}
int main()
{
int t ;
cin>>t ;
while(t--){
   int no ;
   cin>>no ;
 
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
     
  int sum,max ;
  sum=arr[0] ;
  max=arr[0] ;

  for(int i=1;i<no;i++){
      sum=maxof(arr[i],sum+arr[i]) ;
      max=maxof(sum,max) ;
  }
  cout<<max<<endl ;
}
return 0;
}

--------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )