Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find the largest sum of a sequential in int subarray in C

2 Answers

0 votes
#include <stdio.h> 
 
int maxSumOfSubArray(int a[], int size);
 
int main(void)
{
    int arr[] = {-4, -3, 4, -1, -2, 1, 9, -5, 2};
    int max = maxSumOfSubArray(arr, sizeof(arr)/sizeof(arr[0]));
    
    printf("Maximum sequential sum is %d\n", max); // Maximum sequential sum is 11

    return 0;
}

int maxSumOfSubArray(int a[], int size)
{
   int max = 0, sum_to_i = 0, i;
   
   for(i = 0; i < size; i++)
   {
     sum_to_i = sum_to_i + a[i];
     if(sum_to_i < 0)
        sum_to_i = 0;
     if(sum_to_i > max)
        max = sum_to_i;
    }
    return max;
} 

// How it workes:
// -4 -> 0 | -3 -> 0 | 4 -> 4 | 4 -1 -> 3 | 3 -2 -> 1 | 1 1 -> 2 | 2 9 -> 11 | 11 - 5 -> 6 | 6 2 -> 8
// it's clear that the max is 11

/*
run:
   
Maximum sequential sum is 11

*/


answered Mar 1, 2015 by avibootz
edited Mar 1, 2015 by avibootz
0 votes
#include <stdio.h>
 
int maxSumOfSubArray(int a[], int size);
 
int main(void)
{
    int arr[] = {-4, -3, 4, -1, -2, 1, 9, -5, 2, 6, -12};
    int max = maxSumOfSubArray(arr, sizeof(arr)/sizeof(arr[0]));
    
    printf("Maximum sequential sum is %d\n", max); // Maximum sequential sum is 14

    return 0;
}

int maxSumOfSubArray(int a[], int size)
{
   int max = 0, sum_to_i = 0, i;
   
   for(i = 0; i < size; i++)
   {
     sum_to_i = sum_to_i + a[i];
     if(sum_to_i < 0)
        sum_to_i = 0;
     if(sum_to_i > max)
        max = sum_to_i;
    }
    return max;
} 
// How it workes:
/* -4 -> 0 | -3 -> 0 | 4 -> 4 | 4 -1 -> 3 | 3 -2 -> 1 | 1 1 -> 2 | 2 9 -> 11 | 11 - 5 -> 6 |
   6 2 -> 8 | 8 6 -> 14 | 14 | 14 -12 -> 2 */
// it's clear that the max is 14
/*
run:
   
Maximum sequential sum is 14

*/


answered Mar 1, 2015 by avibootz

Related questions

...