Search code examples
cellipsis

How to find max sum of sub array ellipses


I'm trying to find the max sum of sub array using an ellipses function. (And without the use of an array).

Example

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

Desired Output

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

There are lots of algorithms to do this like brute force, divide and conquer and ect' but they all involve arrays and accessing numbers from a certain index.

My code so far:

#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);
}

My problem is that I have to go through all the indexes and that I can't just write list[x], Any leads or ideas would be much appreciated.

Thanks in advance.


Solution

  • First, my approach:

    #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));
    }
    

    I'm looking for the greatest distance of the current partial sum and the minimum found so far. To do this, one does not need random access, so no array is needed. The first parameter, n, is the input size.

    But as you cannot pass variable sized data to this function, its probably not very usefull