找出最长连续递增子序列

题目

给定一个顺序存储的线性表,请设计一个算法查找该线性表中最长的连续递增子序列。
例如,(1,3,5,4,7,9,11,6,54,76,55,56,57,59,60,61)中最长的递增子序列为(55,56,57,59,60,61)。

思路

  • 循环整个数组,前后比较大小,如果前面的数大于后面的,则+1重新放到一个新数组里面;
  • 从新数组中获取最大长度的数组,并取出;

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$arr = [1,3,5,4,7,9,11,6,54,76,55,56,57,59,60,61];
//暴力破解=》归类
$k = 0;
$newArr = array();
foreach ($arr as $index => $value) {
if ($arr[$index+1] > $arr[$index]) {
$newArr[$k][] = $value;
} else {
$newArr[$k][] = $value;
$k++;
}
}
//取值
$key = 0;
$maxlen = 0;
foreach ($newArr as $index => $value) {
$maxlen = max($maxlen, count($newArr[$index]));
if ($maxlen == count($newArr[$index])) {
$key = $index;
}
}

echo '索引为:'. $key .'******元素个数为:'. $maxlen;
print_r($newArr);

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
索引为:3******元素个数为:6
Array(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 5
)

[1] => Array
(
[0] => 4
[1] => 7
[2] => 9
[3] => 11
)

[2] => Array
(
[0] => 6
[1] => 54
[2] => 76
)

[3] => Array
(
[0] => 55
[1] => 56
[2] => 57
[3] => 59
[4] => 60
[5] => 61
)

)
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!