I have the following problem: A sequence of numbers is said to be monotonically increasing (or simply increasing) if every
number in the sequence is greater than, or equals to, the number preceding it. write a boolean function increasing(int[] x, int length)
that returns true if the given array contains an increasing subsequence of the given length, and false otherwise. The guidelines:
?
increasing(int[] x, int length)
I thought about using an old problem, longest increasing subsequence, and then comparing the sizes, if the size given is larger then LIS, it would return false. However my code for LIS seems to be missing cases that skip a number and repeat a number, for example 9,7,5,4,7,1,-3,8
return false for 3 instead of true, also for 3,1,1,2
returns false.
public static boolean increasing(int[] x, int length) {
int i = 0;
int ans = longestIncreasing(x, length, i);
return (ans >= length);
}
private static int longestIncreasing(int[] arr, int n, int i) {
if (n == 0) {
return 1;
}
int m = 1, temp;
if (arr[i++] < arr[n--]) {
temp = 1 + longestIncreasing(arr, n, i);
if (temp > m) {
m = temp; // m = max(m, 1 + _lis(arr, i));
}
}
else {
longestIncreasing(arr, n--, i++);
}
return m;
}
public static boolean increasing(int[] x, int length) {
return increasing(x, length, x[0], 0, 0) >= length;
}
private static int increasing(int[] x, int length, int min, int i, int from) {
if (i >= x.length)
return 0;
int res = increasing(x, length, Math.max(min, x[i]), i + 1, from);
if (x[i] >= min)
res++;
if (i != from || res >= length || i + length > x.length)
return res;
return increasing(x, length, x[i + 1], i + 1, i + 1);
}
Demo:
public static void main(String... args) {
System.out.println(increasing(new int[] { 3, 1, 1, 2 }, 3)); // true
System.out.println(increasing(new int[] { 9, 7, 5, 4, 7, 1, -3, 8 }, 3)); // true
}