I am learning C and my teacher gave me a task, but I'm stuck. In array there are 10 positive numbers and I need to find 3 consecutive numbers with the highest sum. I found this solution online, but how do I find 3 consecutive numbers and sum them? How should I approach this? Should I look for largest number in the array and go from there? The code I found did a better job of what I had done so far.
The array has: {1, 2, 3, 2, 0, 5, 1, 6, 0, 1} then the largest sum of 3 numbers would be {1, 2, 3, 2, 0, 5, 1, 6 , 0, 1} as it gives 12
#define N_ELEMENTS 10
int main(int argc, const char * argv[]) {
int a[N_ELEMENTS] = {1, 2, 3, 2, 0, 5, 1, 6, 0, 1};
int i = 0;
while(a[i] < 0 && i<N_ELEMENTS) {
i++;
}
if (a[i] < 0) {
printf ("DEBUG: array with only negative numbers. Print the smallest negative number as the sum and we are done.\n");
}
int sum_p=0, sum_n = 0;
int largest_sum = 0;
while (i<N_ELEMENTS) {
if (a[i] > 0) {
sum_p += a[i];
}
else {
sum_n += a[i];
}
if (sum_p+sum_n > largest_sum) {
largest_sum = sum_p + sum_n;
}
if (sum_p+sum_n <= 0) {
// find the next positive number
while(a[i] < 0 && i<N_ELEMENTS) {
i++;
}
if (a[i] < 0 || i == N_ELEMENTS) {
break;
}
sum_p = 0;
sum_n = 0;
} else {
i++;
}
}
printf ("DEBUG: The largest consecutive sum = %d\n", largest_sum);
}
what you should do is try every possible consecutive three numbers and choose the best from them something like that
int sum = 0;
int idx = 0
for(int i=0;i<size-2;i++){
if (A[i]+A[i+1]+A[i+2] > sum){
sum = A[i] + A[i+1] + A[i+2];
idx = i;
}
}
the answer is A[idx],A[idx+1],A[idx+2]
All you need is a rolling sum. A sliding window. You can scan linearly in O(n).
Subtract the number that's just slid out of the window and add the new number that arrived. Keep track of the biggest sum.
1, 2, 3, 2, ...
------- sum is 6
-------- sum is 6 - 1 + 2 = 7 (biggest sum.. so far)
------- ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.