Objective: Using a JAVA code, find the number of decreasing sequences in the array and also find the length of its longest decreasing sequence:
Suppose the array has the following elements:
| 9 | 8 | 7 | 8 | 2 | 8 | 6 | 4 | 2 | 9 | 8 | 5 |
In this array following decreasing order sequences can be observed:
| 9 | 8 | 7 |
| 8 | 2 |
| 8 | 6 | 4 | 2 |
| 9 | 8 | 5 |
Out of these the longest sequence in decreasing order, found int above array is clearly having elements:
| 8 | 6 | 4 | 2 |
Now we are supposed to write a java program that reads an array and gives the following outputs:
- Count of all the sequences in descending order
- Find the biggest sequence
Source code is given below:
class desc_seq
{
public static void main(String args[])
{
int num[]={10,9,1,0,10,9,10,8,5,13,1};
int i=0;
int j=0;
int count=0,prevcount=0,prev=num[0];
int counter=0,seqcount=0;
for(i=j;i<=10;)
{
while( prev>=num[i] && i<=10)
{
count++;
prev=num[i];
if(i==10)
{
break;
}
if(i<10)
{
i++;
}
}
if(prev<num[i]|| i==10)
{
counter=count;
System.out.println("this sequence has count of"+counter);
prev=num[i];
count=0;
seqcount++;
}
if(counter>prevcount)
{
prevcount=counter;
}
}
System.out.println("longest sequence is "+prevcount);
System.out.println("no of sequences are "+seqcount);
}
}
Teaching, Coding and Sharing is his passion. A true mentor and motivator. C/C++, Python, Java, Web Technologies (html5 / CSS/ Javascript/ JQuery,Bootstrap, nodeJS ,PHP etc.) and a WordPress enthusiast with more than two decades of experience.
