CHGM1 - Editorial

PROBLEM LINK:

Practice

Contest

Author: Md Shahid

Tester: Arkapravo Ghosh

Editorialist: Md Shahid

DIFFICULTY:

Easy

PREREQUISITES:

Array and loop

PROBLEM:

You need to find longest sum contiguous subarray.

EXPLANATION:

At the end of the game everyone has some point it may be either positive or negative. We need to find the maximum sum of contigous elements. This type of problem is easily solved by the Kadane’s algorithm.

Algorithm:

  Initialize:
  max_so_far = 0
  max_ending_here = 0
  Loop for each element of the array
   (a) max_ending_here = max_ending_here + a[i]
   (b) if max_ending_here is less than 0 
          max_ending_here = 0
   (c) if max_so_far is less than max_ending_here 
          max_so_far = max_ending_here
   return max_so_far

The purpose of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive sum compare it with max_so_far and update max_so_far if it is greater than max_so_far

AUTHOR’S AND EDITORIALIST’S SOLUTIONS:

Author’s and editorialist’s solution can be found here.

1 Like

I think this will reduce the Steps:

#include <bits/stdc++.h>
using namespace std;
int KadanesAlgo(vector<int>& v)
{
    int local_max=0,global_max = INT_MIN;
    int n = v.size();
    for(int i=0;i<n;i++)
    {
        local_max = max(v[i] , v[i]+local_max);
        global_max = max(global_max,local_max);
    }
    return global_max;
}
int main() {
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        vector<int> v;
        while(n--)
        {
            int a;
            cin>>a;
            v.push_back(a);
        }
        int res = KadanesAlgo(v);
        cout<<res<<endl;
    }
}