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
Is c still used?
What is type qualifiers?
What is a void * in c?
A function can make the value of a variable available to another by a) declaring the variable as global variable b) Passing the variable as a parameter to the second function c) Either of the two methods in (A) and (B) d) binary stream
What is assert and when would I use it?
Is main is a keyword in c?
How do I read the arrow keys? What about function keys?
What is maximum size of array in c?
What is #error and use of it?
hi folks i m approching for h1 b interview on monday 8th of august at montreal and i m having little problem in my approval notice abt my bithdate my employer has made a mistake while applying it is 12th january and istead of that he had done 18 the of january do any body have any solution for that if yes how can i prove my visa officer abt my real birthdate it urgent please let me know guys thaks dipesh patel
Why use int main instead of void main?
What do you mean by keywords in c?
In C, What is the #line used for?
Write a program to reverse a linked list in c.
Can you please explain the difference between strcpy() and memcpy() function?