【问题标题】:How to find max sum of sub array ellipses如何找到子数组椭圆的最大总和
【发布时间】:2018-09-10 14:09:51
【问题描述】:

我正在尝试使用ellipses function 查找子数组的最大总和。 (并且不使用数组)。

例子

{−2, 1, −3, 4, −1, 2, 1, −5, 4}

期望的输出

{4, −1, 2, 1} = 6

有很多算法可以做到这一点,比如蛮力、分而治之等等,但它们都涉及数组和从某个索引访问数字。

到目前为止我的代码:

#include <stdio.h>
#include <stdarg.h>

int getsum(int x, ...) {
    va_list(list);
    va_start(list,x);
    int k,s;
    for (k=0; k<x; k++) {
        s+=va_arg(list,int *);
    }
    va_start(list,x);
}

我的问题是我必须遍历所有索引 我不能只写list[x], 任何线索或想法将不胜感激。

提前致谢。

【问题讨论】:

  • 为什么不用数组?

标签: c ellipsis


【解决方案1】:

首先,我的方法:

#include <stdio.h>
#include <stdarg.h>
int getsum(int n, ...){
        va_list(list);
        int k,s = 0;
        int maxsum = 0;
        int minsum = 0;

        va_start(list,n);
        for (k=0; k<n; k++){
                s+=va_arg(list,int);
                if(s < minsum){
                        minsum = s;
                }
                if(s - minsum > maxsum){
                        maxsum = s - minsum;
                }
        }
        va_end(list);
        return maxsum;
}

int main(){
        printf("%d\n", getsum(9, -2, 1, -3, 4, -1, 2, 1, -5, 4));
}

我正在寻找当前部分和的最大距离和迄今为止找到的最小值。为此,不需要随机访问,因此不需要数组。第一个参数n是输入大小。

但是由于你不能将可变大小的数据传递给这个函数,它可能不是很有用

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 2017-08-22
    • 1970-01-01
    • 2022-10-12
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多