-1

hello I'm trying to solve an exercise about the sequence of numbers in a list with the greatest sum: I need to write a (non-recursive) function that returns the largest sum of numbers in the list. example: in the list:[-1,4,-10,9,14,-4] need to return 23 because 9+14=23 and its the maximum sum in this list. i'm beeginer in C and don't know how using deboguer with list in C? can you help me to undersand where are my problems?

int sum_lst(int lst[],int debut,int fin){
    int i=debut,sum=0;
    for (i;i<fin;i++){
        sum+=lst[i];
    }
    return sum;
}
int max_sum(int lst[],int n){
    int i=n;
    static int sum;
    int j=0;
    for (i;i>0;i--){
        for (j;j<n;j++){
            if (sum_lst(lst,j,i)>sum){
                sum= sum_lst(lst,i,j);
            }
        }
    }
    return sum;
}
  • Bonjour :), you should first find the two highest number and sum them. It's better if we don't give you the answer ( it is very easy) – GabrielT Mar 19 '21 at 13:31
  • 1
    1> sort the list descending (maybe using library sort) 2> get the first two Items (or the last two if you sort descending) 3> voila – DDS Mar 19 '21 at 13:31
  • @DDS What should be the output for `[10, -20, -30, 40, -50]`? – MikeCAT Mar 19 '21 at 13:33
  • Don't know how to use debugger? Then let's learn! [debugging - What is a debugger and how can it help me diagnose problems? - Stack Overflow](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – MikeCAT Mar 19 '21 at 13:35
  • 50, of course: sorted vector will be `[50, 40, -20, -30, -50]` but it depends on how you implement the comparing function to the sort. Remember: if standard library has a function for it, just use it. – DDS Mar 19 '21 at 13:35
  • Do the numbers have to be adjacent? (i.e. *subarrays*) – Damien Mar 19 '21 at 13:38
  • Does this help? [C / C++ Program for largest sum contiguous subarray](https://www.geeksforgeeks.org/c-program-for-largest-sum-contiguous-subarray/) – Abra Mar 19 '21 at 13:40

1 Answers1

0
  • You forgot to initialize j before each loop at for (j;j<n;j++){
  • You wrongly swapped i and j at sum= sum_lst(lst,i,j);
  • sum is not initialized, so the result may be wrong if max_sum is called multiple times or an array with all negative elements is given.

Fixed code:

int sum_lst(int lst[],int debut,int fin){
    int i=debut,sum=0;
    for (i;i<fin;i++){
        sum+=lst[i];
    }
    return sum;
}
int max_sum(int lst[],int n){
    int i=n;
    static int sum;
    int j=0;
    if (n<=0) return 0;
    sum = lst[0]; /* initialize sum */
    for (i;i>0;i--){
        for (j=0;j<n;j++){ /* initialize j */
            if (sum_lst(lst,j,i)>sum){
                sum= sum_lst(lst,j,i); /* don't swap i and j */
            }
        }
    }
    return sum;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70