题目地址:
https://leetcode.com/problems/longest-non-decreasing-subarray-from-two-arrays/description/
给定两个长 n n n数组 a a a和 b b b,我们构造一个数组 c c c使得 c [ i ] c[i] c[i]可以等于 a [ i ] , b [ i ] a[i],b[i] a[i],b[i]之一,并且使得 c c c的最长非降子数组最长,问这个最长的长度。
设 f [ i ] f[i] f[i]是如果 c [ i ] c[i] c[i]取 a [ i ] a[i] a[i]的话,以 c [ i ] c[i] c[i]结尾的 c c c中最长非降子数组的长度,类似的,设 g [ i ] g[i] g[i]是如果 c [ i ] c[i] c[i]取 b [ i ] b[i] b[i]的话,以 c [ i ] c[i] c[i]结尾的 c c c中最长非降子数组的长度。如果 a [ i ] ≥ a [ i − 1 ] a[i]\ge a[i-1] a[i]≥a[i−1],那么 f [ i ] f[i] f[i]可以由 f [ i − 1 ] + 1 f[i-1]+1 f[i−1]+1更新;如果 a [ i ] ≥ b [ i − 1 ] a[i]\ge b[i-1] a[i]≥b[i−1],那么 f [ i ] f[i] f[i]可以由 g [ i − 1 ] + 1 g[i-1]+1 g[i−1]+1更新。最后的答案是 max i { f [ i ] , g [ i ] } \max_i \{f[i],g[i]\} maxi{f[i],g[i]}。代码如下:
class Solution {
public:
int maxNonDecreasingLength(vector<int>& a, vector<int>& b) {
int n = a.size();
int f[n][2];
memset(f, 0, sizeof f);
f[0][0] = f[0][1] = 1;
int res = 1;
for (int i = 1; i < n; i++) {
f[i][0] = f[i][1] = 1;
if (a[i] >= a[i - 1]) f[i][0] = max(f[i][0], f[i - 1][0] + 1);
if (a[i] >= b[i - 1]) f[i][0] = max(f[i][0], f[i - 1][1] + 1);
if (b[i] >= b[i - 1]) f[i][1] = max(f[i][1], f[i - 1][1] + 1);
if (b[i] >= a[i - 1]) f[i][1] = max(f[i][1], f[i - 1][0] + 1);
res = max(res, max(f[i][0], f[i][1]));
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。