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:
- No loops at all, only recursion
- No lists & imports (so no map or so) &
?
- No changing the signature of the function
increasing(int[] x, int length)
- You may add private functions but not ints/booleans ect.
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;
}
9,7,5,4,7,1,-3,8
for 3 should returntrue
? I see only sequence with 2 numbers4, 7
. – statut