Question

(C programming) Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum...

(C programming) Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.

Input

The input consists of multiple datasets. Each data set consists of:

n
a1
a2
.
.
an

You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.

The input end with a line consisting of a single 0.

Output

For each dataset, print the maximum sum in a line.

Sample Input

7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0

Output for the Sample Input

19
14
1001
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Kadane's algorithm has been used here to find the maximum sum of contiguous array

Editable Code:

# include <stdio.h>

//Implementation of Kadane's algorithm
int maxContiguousSum(int a[], int size) {
int max_ending_here = 0, max_so_far = 0,i;
for ( i = 0; i < size; i++){
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;

   else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}

int main(){
  
   int n;
   scanf("%d", &n);
   if(n>0){
       do{
           int a[5000];
           int i;
           for(i = 0;i<n;i++){ //Taking array input
               scanf("%d", &a[i]);
           }
           printf("%d\n",maxContiguousSum(a,n)); //Calling the fuction to print max sum
           scanf("%d", &n); //Size of next array
       }while(n>0); //Loop runs if size of next array is greater than 0
   }
return 0;
}

Hope this helps
If you have any doubt feel free to comment
Thank You!!

Add a comment
Know the answer?
Add Answer to:
(C programming) Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT