算法分析
初始化:f[0][0] = 0
,f[0][1] = -INF
时间复杂度 $O(n)$
参考文献
算法提高课
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 100010, INF = 0x3f3f3f3f;
static int[] w = new int[N];
static int[][] f = new int[N][2];
static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T -- > 0)
{
n = Integer.parseInt(br.readLine());
String[] s1 = br.readLine().split(" ");
for(int i = 1;i <= n;i ++) w[i] = Integer.parseInt(s1[i - 1]);
f[0][0] = 0;
f[0][1] = -INF;
for(int i = 1;i <= n;i ++)
{
f[i][0] = Math.max(f[i - 1][0], f[i - 1][1]);
f[i][1] = f[i - 1][0] + w[i];
}
System.out.println(Math.max(f[n][0], f[n][1]));
}
}
}