Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ed483af

Browse files
Merge pull request #224 from nandikeshsingh/master
Maximum Subarray Sum
2 parents 8370353 + 9cf8f8c commit ed483af

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Problem : To find the maximum subarray sum.
2+
3+
Language used : C++
4+
5+
Input : An integer array given by the user.
6+
7+
Output : A single integer denoting the maximum subarray sum.
8+
9+
Algorithm Paradigm : Dynamic Programming.
10+
11+
Time Complexity : Linear
12+
13+
Space Complexity : Constant
14+
15+
Working :-
16+
17+
We are traversing the array and storing the sum of contiguous elements in sum variable.
18+
As the value of sum reaches its maximum value that value is stored in max_so_far variable.
19+
And as the value of sum becomes negative,we are setting the value of sum again to 0 as now its time to look for another subarray as the net sum of the elements of the previous subarray became negative.
20+
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//Code to find the maximum subarray sum using dynamin programming in c++.
2+
#include<bits/stdc++.h>
3+
4+
using namespace std;
5+
6+
int main()
7+
{
8+
int n;
9+
cout<<"Enter the size of the array : ";//Inputting the size of the array.
10+
cin>>n;
11+
cout<<endl;
12+
13+
int arr[n];
14+
for(int i=0;i<n;i++)
15+
{
16+
cout<<"Enter the value of element "<<i+1<<" : ";
17+
cin>>arr[i];//Inputting the values in the array.
18+
}
19+
20+
int max_so_far=-99999;//It will store the maximum subarray sum.
21+
int sum=0;//It will store the sum of the different subarrays.
22+
23+
for(int i=0;i<n;i++)//Implementing the kadane's Algorithm.
24+
{
25+
sum+=arr[i];
26+
if(sum>max_so_far)
27+
max_so_far=sum;
28+
if(sum<0)
29+
sum=0;
30+
}
31+
32+
cout<<"The maximum subarray sum is : "<<max_so_far<<endl;//Printing the answer i.e the maximum subarray sum.
33+
34+
return 0;
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /