Skip to content

Commented the Whole code for better understanding #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions largest sum of subarray.cpp
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
#include<bits/stdc++.h>
#include<bits/stdc++.h> //Including header file
using namespace std;
int main(){
int n,el,i,j,max;
cout << "Enter size of array " << endl;
cin >> n;
int data[n];
cout << "Enter the elements " << endl;
for (i=0;i<n;i++){
cin >> el;
data[i] = el;
int main(){ //Main Function
int n,el,i,j,max; //Declaring variables
cout << "Enter size of array " << endl; //getting the size of array
cin >> n; // Storing that value in var n
int data[n]; //Defining an array of size n
cout << "Enter the elements " << endl;
for (i=0;i<n;i++){ //
cin >> el; // Getting all array value and storing it in the prev created array
data[i] = el; //
}
int ans[n];
ans[0] = data[0];
for (i=1;i<n;i++){
if (ans[i-1] + data[i] > data[i]){
ans[i] = data[i] + ans[i-1];
}
else{
ans[i] = data[i];
int ans[n]; //Creating a new array 'ans'
ans[0] = data[0]; //First value of ans = First value in data
for (i=1;i<n;i++){ //Iterative Loop for n times
if (ans[i-1] + data[i] > data[i]){ //Condition check if value at 'ans' and corresponding next value in data sum is greater than data[i]
ans[i] = data[i] + ans[i-1]; //If so, that is the current max sub array sum
}
else{
ans[i] = data[i]; // Else value without adding is the max sub array sum
}
}
max = -100000;
for (i=0;i<n;i++){
if (max < ans[i]){
max = ans[i];
max = ans[i]; //Finding the ultimate max value from the above obtained values
}
}
cout << "Sum of largest subarray is " << max << endl;
cout << "Sum of largest subarray is " << max << endl; // That would be the max sub array sum
return 0;
}
}