If we have an array of Interger values, find out a sub array
which has a maximum value of the array and start and end
positions of the array..The sub array must be contiguious.
Take the start add to be 4000.

For Ex if we have an array arr[] =
{-1,-2,-5,9,4,3,-6,8,7,6,5,-3}

here the sub array of max would be
{8,7,6,5} coz the sum of max contiguous array is 8+7+6+5 =
26.The start and end position is 4014(8) and 4020(5).

Answer Posted / kyle

Here's another way...
Btw this way gets the correct answer of {9,4,3,-6,8,7,6,5}
with a sum of 36.

#include <stdio.h>
#include <stdlib.h>

#ifndef NULL
#define NULL 0
#endif

struct index {
int start;
int finish;
int sum;
};

int main()
{
// Init and setup variables
struct index max; // Max values
struct index cur; // Current values
int avg = 0; // Average values
int len = 0; // Array length
int* a = NULL; // The array
int i;

//Get values
printf("Enter the number of variables in the array:");
scanf("%d", &len);

array = malloc(len*sizeof(int));

if( array == NULL )
{
printf("Error: Out of memory");
return 0;
}

for(i=0; i<len; ++i)
{
scanf("%d",&a[i]);
avg += a[i];
}
avg /= len; // Compute average

max.start = max.finish = 0;
max.sum = a[0];

for(i=0; i<len && max.finish != len; ++i)
{
cur.start = cur.finish = i;
cur.sum = a[i];
while( cur.sum > avg && cur.finish < len )
{
if( cur.sum > max.sum )
{
max.start = cur.start;
max.finish = cur.finish;
max.sum = cur.sum;
}
++cur.finish;
if( cur.finish < len )
cur.sum += a[cur.finish];
}
}

printf("\n Max sum = %d, start = %d, finish = %d\n",
max.sum, max.start, max.end);
return 0;
}

Is This Answer Correct ?    1 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

explain what are actual arguments?

639


in multiple branching construct "default" case is a) optional b) compulsarily c) it is not include in this construct d) none of the above

637


What is the heap in c?

647


What are the rules for the identifier?

676


Explain the difference between call by value and call by reference in c language?

651






What is the acronym for ansi?

633


What are the 5 types of inheritance in c ++?

589


Where register variables are stored in c?

554


What is call by value in c?

562


What is the difference between constant pointer and constant variable?

751


How important is structure in life?

595


What is difference between array and structure in c?

583


What is calloc in c?

665


What is an endless loop?

806


Why is c called c not d or e?

616