Subarray of maximum Sum of a given Array O(n)!!!! (kadane algorithm)

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,i,j,k,sum,right,max_sum,s;
    cout<<"enter the size of array : \n";
    cin>>n;
    int a[n];
    for(i=0;i<n;i++)
    cin>>a[i];
    
    max_sum=-1;
    right=-1;
    sum=0;
    
    for(i=0;i<n;i++)
    {
        sum+=a[i];
        if(sum<0)
        {
            sum=0;
        }
        else if(sum>max_sum)
        {
            max_sum=sum;
            right=i;
        }
    }
    s=max_sum;
    
    cout<<"The maximum sum will be: "<<max_sum<<endl;

    //print the array from the right pos of max sum until...
    //....max sum becomes zero.

    cout<<"The subarray will be: ";
    for(i=right;s!=0;i--)
    {cout<<a[i]<<" ";
    s-=a[i];}
    //subarray is printed in reverse order....
}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree