Create a variable holding current maximum length and a variable holding current length.
If current value minus 1 and then is equals to previous value, increase current length by 1.
otherwise, if current length is greater than current maximum length variable, then update this variable, and set the current length 1
at last return current maximum length
Code
public int findLongestSubarray(int[] nums) {
int maxLength = 0;
int length = 0;
for (int i = 0; i < nums.length; i++) {
if (i == 0 || nums[i] == nums[i - 1] + 1) {
length++;
} else {
if (length > maxLength) { maxLength = length;
}
length = 1;
}
}
if (length > maxLength) {
maxLength = length;
}
return maxLength;
}
Find Longest Continuous Increasing Subsequence
Algorithm
Let S[pos] be defined as the smallest integer that ends an increasing sequence of length pos + 1
Append current if it is greater than last element
replace smallest element that is greater than current if current is smaller or equal to last element
Code
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// tailTable[i] is defined as index of smallest integer that ends an increasing sequence of length i + 1.
int[] tailTable = new int[nums.length];
// parent[i] is defined as index of predecessor of element with index i
int[] parent = new int[nums.length];
Arrays.fill(parent, -1);
int len = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[tailTable[len - 1]]) {
// if current integer > last element in LIS, append this integer to the end of LIS
tailTable[len] = i;
parent[i] = tailTable[len - 1]; // current integer's predecessor is last element of previous LIS
len++; // increase length of LIS
} else {
// otherwise, find index of smallest integer in LIS, the integer >= current integer
int index = ceilIndex(tailTable, nums, len - 1, nums[i]);
parent[i] = parent[tailTable[index]]; // current integer's predecessor is predecessor of replaced integer
tailTable[index] = i; // replace
}
}
int index = tailTable[len - 1];
// print LIS
Stack<Integer> stack = new Stack<Integer>();
while (index != -1) {
stack.push(index);
index = parent[index];
}
while (!stack.isEmpty()) {
System.out.print(nums[stack.pop()] + " ");
}
System.out.println();
return len;
}
/**
* find index of smallest integer in tailTable, the integer >= target
*/
private int ceilIndex(int[] tailTable, int[] nums, int end, int target) {
int start = 0;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[tailTable[mid]] >= target) {
end = mid;
} else {
start = mid;
}
}
if (target <= nums[tailTable[start]]) {
return start;
} else {
return end;
}
}