Skip to content

Commit ceff98c

Browse files
authored
Create Kadane's_algorithm.cpp
1 parent 078f936 commit ceff98c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Kadane's_algorithm.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//
2+
// main.cpp
3+
//
4+
// Created by Prince Kumar on 21/04/20.
5+
// Copyright © 2020 Prince Kumar. All rights reserved.
6+
//
7+
// ---** MAX SUM CONTIGUOUS SUBARRAY **---
8+
9+
#include <iostream>
10+
#include <vector>
11+
#include <algorithm>
12+
using namespace std;
13+
int main(){
14+
cout<<"Enter the size of Array : "<<endl;
15+
int n; cin>>n;
16+
17+
int a[n];
18+
for(int i=0;i<n;i++){
19+
cin>>a[i];
20+
}
21+
22+
int max_so_far = a[0], max_ending_here =0; // It store sum
23+
int start = 0 , end=0 , s=0; // it store index
24+
25+
for(int i=0;i<n;i++){
26+
max_ending_here+=a[i];
27+
if(max_so_far < max_ending_here){
28+
max_so_far=max_ending_here;
29+
start = s; end=i;
30+
}
31+
32+
if(max_ending_here<0){
33+
max_ending_here = 0;
34+
s = i+1;
35+
}
36+
}
37+
38+
int sum=0;
39+
for(int i=start ;i<=end ; i++){
40+
sum+=a[i];
41+
cout<<a[i]<<" ";
42+
43+
}
44+
cout<<endl;
45+
cout<<sum<<endl;
46+
47+
48+
}

0 commit comments

Comments
 (0)