您的位置:首页 > 产品设计 > UI/UE

#397 Longest Increasing Continuous Subsequence

2016-08-18 13:49 295 查看
题目描述:

Give an integer array,find the longest increasing continuous subsequence in this array.
An increasing continuous subsequence:
Can be from right to left or from left to right.
Indices of the integers in the subsequence should be continuous.


 Notice


O(n) time and O(1) extra space.

Have you met this question in a real interview? 

Yes

Example

For 
[5, 4, 2, 1, 3]
,
the LICS is 
[5, 4, 2, 1]
, return 
4
.
For 
[5, 1, 2, 3, 4]
,
the LICS is 
[1, 2, 3, 4]
, return 
4
.

题目思路:

这题用了一点dp的思想:用local来记录小范围内的增长/减少subarray的长度,如果local_inc遇到减少的情况,就reset成1;用global来记录最长的长度,取自己和local的max。

Mycode(AC = 22ms):

class Solution {
public:
/**
* @param A an array of Integer
* @return an integer
*/
int longestIncreasingContinuousSubsequence(vector<int>& A) {
// Write your code here
int local_inc = 1, local_dec = 1;
int global_inc = 1, global_dec = 1;

if (A.size() <= 2) return A.size();

// local_inc to record locally max increasing length
// local_dec to record locally max decreasing length
for (int i = 1; i < A.size(); i++) {
if (A[i] >= A[i - 1]) {
local_inc++;
global_inc = max(global_inc, local_inc);
local_dec = 1;
}
else {
local_dec++;
global_dec = max(global_dec, local_dec);
local_inc = 1;
}
}

return max(global_inc, global_dec);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息