HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java implementation of the longest monotone increasing subsequence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thesubsequencemonotonejavaincreasingimplementationlongest

Problem

Problem: Given a set of n distinct numbers, find the length of the longest monotone increasing subsequence.
For example, let's take this array [1,2,9,4,7,3,11,8,14,6]
The longest monotone increasing subsequence of this array is [1,2,4,7,11,14]. So the desired result is, the length of the array which is 6.

Algorithm (taken from R.G. Dromey's How to Solve it by computer):

  • Establish the data set a[1...n] of n elements.



  • Set two loops, one to find out out each terminating point and the inner loop to find it's increasing subsequence.



  • start the first loop at index 2 so that it will initially have a sequence.



  • in the inner loop,


if current element is less than maximum of previous sequence, then,
identify the subsequence and if the length of subsequence is larger than the length of previous longest subsequence then update the length, position of maximum and maximum value.

else, update the length, position of maximum and maximum value so far.

```
import java.util.*;

public class Monotone {

public static int maxMonotonicSequenceLength(int[] elements) {
int maxValue = 0;
int positionOfMax = 0;
int length = 2;

for (int i = 2; i < elements.length; ++i) {
if (elements[i] < maxValue) {
int count = 1;
int previousMaxElement = 0;

for (int j = 1; j <= i-1; ++j) {
if ((elements[j] < elements[i]) &&
previousMaxElement < elements[j]) {

previousMaxElement = elements[j];
count = count + 1;
if (length < count) {
length = count;
positionOfMax = j;
maxValue = elements[j];
}
}
}
} else {
positionOfMax = i;
maxValue = elements[i];
length = length + 1;
}
}
return length + 1;
}

public static void main(String args[]) {
int[] list = new int[10];

list[0] = 1;
list[1] = 2;
list[2] = 9;
list[3] = 4;
list[4] = 7;
list[5] = 3;

Solution

Coding details

  • You can initialize list like this : int[] list = {1,2,9,4,7,3,11,8,14,6};



  • for (int j = 1, n = i-1; j



  • length++; // for length = length + 1;`

Context

StackExchange Code Review Q#16327, answer score: 2

Revisions (0)

No revisions yet.