简体   繁体   English

C数组中3个连续数字的最大和

[英]C largest sum of 3 consecutive numbers from array

I am learning C and my teacher gave me a task, but I'm stuck. 我正在学习C,我的老师给了我一个任务,但我被困住了。 In array there are 10 positive numbers and I need to find 3 consecutive numbers with the highest sum. 在数组中有10个正数,我需要找到三个具有最高和的连续数。 I found this solution online, but how do I find 3 consecutive numbers and sum them? 我在网上找到了该解决方案,但是如何找到3个连续的数字并将它们求和? 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 数组具有:{1、2、3、2、0、5、1、6、0、1},则3个数字的最大和为{ 1、2、3、2、0、5、1、6 ,0,1},因为它给出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] 答案是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). 您可以在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)
      -------  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM