小牛送草

private static int[] dp;

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    while (t-- > 0) {
        int N = in.nextInt();
        dp = new int[N];
        int[] values = new int[N];
        for (int i = 0; i < N; i++) {
            values[i] = in.nextInt();
        }
        System.out.println(Math.max(sell(values, 0, N - 2), sell(values, 1, N - 1)));

    }
}

private static int sell(int[] values, int first, int last) {
    if (last - first == 0) return values[first];
    if (last - first == 1) return Math.max(values[first], values[last]);
    dp[first] = values[first];
    dp[first + 1] = values[first + 1];
    dp[first + 2] = values[first] + values[first + 2];
    for (int i = first + 3; i <= last; i++) {
        dp[i] = Math.max(dp[i - 2], dp[i - 3]) + values[i];
    }
    return Math.max(dp[last], dp[last - 1]);
}

猜你喜欢

转载自blog.csdn.net/lulu950817/article/details/80043457
今日推荐