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
explain what are actual arguments?
in multiple branching construct "default" case is a) optional b) compulsarily c) it is not include in this construct d) none of the above
What is the heap in c?
What are the rules for the identifier?
Explain the difference between call by value and call by reference in c language?
What is the acronym for ansi?
What are the 5 types of inheritance in c ++?
Where register variables are stored in c?
What is call by value in c?
What is the difference between constant pointer and constant variable?
How important is structure in life?
What is difference between array and structure in c?
What is calloc in c?
What is an endless loop?
Why is c called c not d or e?