题解 | #最长严格上升子数组(一)#
最长严格上升子数组(一)
http://www.nowcoder.com/practice/78889543865f4aa380fa69e641ad9889
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int maxSubArrayLengthTwo(int[] nums) {
// write code here
if (nums.length < 2) {
return nums.length;
}
if (nums.length == 2) {
return nums[0] == 100000 ? 1 : 2;
}
int[] dp = new int[nums.length];
Arrays.fill(dp, Integer.valueOf(1));
int ans = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
dp[i] = dp[i - 1] + 1;
ans = Math.max(ans, dp[i]);
}
}
for (int currentIndex = 1; currentIndex < dp.length; currentIndex++) {
if (dp[currentIndex] == 1) {
ans = Math.max(ans, dp[currentIndex - 1] == 100000 ? dp[currentIndex] : dp[currentIndex - 1] + 1);
continue;
}
int previousIndex = currentIndex - dp[currentIndex];
if (previousIndex > -1 && nums[previousIndex + 1] > 1) {
ans = Math.max(ans, dp[currentIndex] + 1);
}
if (previousIndex > -1 && nums[previousIndex + 2] - nums[previousIndex] >= 2) {
ans = Math.max(ans, dp[currentIndex] + dp[previousIndex]);
}
if (previousIndex - 1 > -1 && nums[previousIndex + 1] - nums[previousIndex - 1] >= 2) {
ans = Math.max(ans, dp[currentIndex] + dp[previousIndex]);
}
}
return ans;
}
}