sum of elements in a list

Hi again :)

This time I'm supposed to write something that seems like it should be so easy to write but for some reason I can't figure it out. This is part of a larger program, but it's also the core part of it.

So, I'm supposed to write a function that gives the highest sum of non-null consecutive elements of a list.

For example:

For {1, 2, 0, 6, 2, 4, 0, 1, 5} we have 3 sums:
sum1 = 1+ 2 => sum1 = 3;
sum2 = 6 + 2 + 4 => sum2 = 12;
sum3 = 1 + 5 => sum3 = 6;

The function is supposed to return only 12 as the highest sum.

All the functions I've written so far either stop at the first 0 they encounter and if that 0 is actually the first element in the list it says the sum is 0 or if there actually were other numbers before that 0 it returns whatever sum it got up to that 0 but it doesn't move on to the next elements of the list where it may encounter a higher sum, or it simply returns the sum of all the numbers in the list.

I don't know how to tell it that when it reaches a 0 to simply record the sum obtained til that moment and move on from 0 to the next element.

I'll wait, maybe you guys give me some ideas. I'm not sure yet which of my 8 versions of code I should post. Probably one of those that just stop at 0s?

EDIT:

I'll just post the one I'm working on now. This one just gives me 1. Argh!! I don't get it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
using namespace std;

int max_sum(vector<int>& tab)
{
	int sum = 0, sum_max(0);
	
	for(size_t i(0); i < tab.size(); ++i){
		if(tab[i] == 0){
			if(sum > sum_max){
				sum_max = sum;
				return sum_max;
			}else{
				return sum_max;
			}
			sum = 0;
			return sum;
		}else{
			sum = sum + tab[i];
			return sum;
		};
	}
	
	return sum;
}


int main()
{
	vector<int> tab({1, 2, 0, 6, 2, 4, 0, 1, 5});
	cout << "max sum is: " << max_sum(tab) << endl;
	
	return 0;
}
Last edited on
I'm iterating over a list.
I have two values in memory: current running sum and the maximum so far.
I get the next value X. I have two choices:

1. X is 0. Current running sum is now 0.
2. X is not 0. Add X to running sum. If sum is larger than max, then update max.
Topic archived. No new replies allowed.