2016-level algorithm final simulation practice race-b.alvinzh Youth Memory I

Source: Internet
Author: User

1083 Alvinzh's youth memory I thought

Medium problem, dynamic planning.

Simplify the test instructions, take the number on a ring, the number is not adjacent, take the sum of the maximum value.

Ring bad, can be solved into a column number, then the answer should be the following two cases of the larger.

①: Take the first point, you can get the maximum value for the treasure [1,n-1] the maximum value.

②: Do not take the first point, can get the maximum value for the treasure [2,n] the maximum value.

Dynamic programming, state transition equation:\ (Dp[i] = max (dp[i-1], dp[i-2] + v[i])

Analysis

Time complexity:\ (O (n) \).

Reference Code
////Created by Alvinzh on 2017/12/4.//Copyright (c) alvinzh. All rights reserved.//#include <cstdio>#include <iostream>#define MAX (A, b) a > B? a:busing namespaceStdintNintv[100005];/*int dp[100005];int MaxValue (int left, int. right){Dp[left] = V[left];dp[left+1] = max (V[left], v[left+1]);for (int i = left+2; I <= right; i++)Dp[i] = max (dp[i-1], dp[i-2] + v[i]);return dp[right];}*///Optimize codeintMaxValue (intLeftintright) {intLasttwo =0, LaStone =0; for(inti = left; I <= right; i++) {inttemp = LaStone;        LaStone = Max (LaStone, Lasttwo + v[i]);    Lasttwo = temp; }returnLaStone;}intMain () { while(~SCANF ("%d", &n)) { for(inti =1; I <= N; i++) scanf ("%d", &v[i]);if(n = =1) printf ("%d\n", v[1]);Elseprintf"%d\n", Max (MaxValue (1+ I-1), MaxValue (2, n))); }}

2016-level algorithm final simulation practice race-b.alvinzh Youth Memory I

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.