File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments