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 / vadivelt
Hi All,
I hope the code which i have written ll give the exact
answer
Note: Compiler used is visual Studio 2005
Eg: if the the no of elemet is 12 and the elements are -1,-
2,5,6,-4,7,8,9,-3,10,20,-4 then output(sub array) should
contain the elements 10
and 20.
#include<stdio.h>
#include<conio.h>
int MakeSubArray(int *ptr, int size);
main()
{
int array[100];
int subarray[10], Index, no, j, k;
printf("ENTER NO OF ELEMENTS IN THE MAIN ARRAY \n");
scanf("%d", &no);
printf("\nENTER THE ELEMENTS\n");
for(j = 0; j<no; j++)
{
scanf("%d", &array[j]);
}
Index = MakeSubArray(&array[0],no);
printf("\nSTART POSITION\n%d", &array[Index]);
printf("\n\nSUB ARRAY ELEMENT(S) \n");
for(j = Index, k = 0; (array[j] >= 0) && (j < no);
j++, k++)
{
subarray[k] = array[j];
printf("%d ", subarray[k]);
}
printf("\n\nEND POSITION\n%d", &array[j-1]);
getch();
}
int MakeSubArray(int *ptr, int size)
{
int i, flag = 0, sum = 0, sum1 = 0, index = 0,
index1;
if(ptr != '\0' && size > 0)
{
for(i = 0; i <size; i++)
{
if(ptr[i] >= 0)
{
if(flag == 0)
{
index = i;
}
sum = sum + ptr[i];
flag++;
}
else
{
if(flag > 0 && sum1 < sum)
{
index1 = index;
sum1 = sum;
}
sum = 0;
flag = 0;
}
}
/*If the last element is non zero and it is part of
sub array then this condition is useful*/
if(flag > 0 && sum1 < sum)
{
index1 = index;
}
}
return index1;
}
| Is This Answer Correct ? | 1 Yes | 1 No |
Post New Answer View All Answers
Is c programming hard?
what will be the output for the following main() { printf("hi" "hello"); }
What is the difference between declaring a variable by constant keyword and #define ing that variable?
Can you assign a different address to an array tag?
What is the full form of getch?
What is a good data structure to use for storing lines of text?
What is non linear data structure in c?
What is c variable?
Write a program to print ASCII code for a given digit.
cin.ignore(80, _ _);This statement a) ignores all input b) ignores the first 80 characters in the input c) ignores all input till end-of-line d) iteration
Explain c preprocessor?
What will the preprocessor do for a program?
What is omp_num_threads?
Does c have an equivalent to pascals with statement?
Write a c program to demonstrate character and string constants?