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
What is dynamic variable in c?
write a program to convert a expression in polish notation(postfix) to inline(normal) something like make 723+* (2+3) x 7 (not sure) just check out its mainly printing expression in postfix form to infix.
Explain function?
What is local and global variable in c?
Explain how can I convert a string to a number?
Write a program in "C" to calculate the root of a quadratic equation ax^2+bx+c=0, where the value of a,b & c are known.
what is different between auto and local static? why should we use local static?
What are the various types of control structures in programming?
When should a far pointer be used?
If fflush wont work, what can I use to flush input?
What are the properties of union in c?
What is the use of linkage in c language?
in programming languages a statement or part of a statement that specifies several different execution sequences a) constructs b) distructs c) executes d) none
write a c program to calculate sum of digits till it reduces to a single digit using recursion
how many key words availabel in c a) 28 b) 31 c) 32