Maximum cost of 51nod1270 array (simple DP)

Source: Internet
Author: User

---restore content starts---

1270 the maximum cost of an array source: Hackerrank Base time limit: 1 seconds space limit: 131072 KB score: 20 Difficulty: 3-level algorithm problem collection concern array A contains n elements A1, A2 ... An. Array B consists of n elements B1, B2 ... BN. And each element of the array, AI, satisfies 1 <= ai <= Bi. The cost of array A is defined as follows: (the formula represents the sum of the absolute values of the difference of all two adjacent elements) given to arrays B, calculating the possible maximum cost S. Input
Line 1th: 1 number N, indicating the length of the array (1 <= n <= 50000). Line 2-n+1:1 numbers per line, corresponding to array element bi (1 <= bi <= 10000).
Output
The maximum cost of output s.
Input example
510110110
Output example
36
To see this problem first think about it | Ai-a (i-1) | Max, this A array can only be 1 or bi
The case of 1 or bi is considered separately;
You can get a recursive formula:
Dp[i][0]=max (Dp[i-1][0],dp[i-1][1]+abs (1-b[i-1)); Indicates a condition of a[i] to 1
Dp[i][1]=max (Dp[i-1][0]+abs (b[i]-1]), Dp[i-1][1]+abs (B[i]-b[i-1])), or/= A[i] for bi
#include <stdio.h> #include <algorithm> #include <iostream>using namespace Std;int b[50005];int dp[ 50005][2];int Main () {    int n;    scanf ("%d", &n);    int i;    for (i=0;i<n;i++)        scanf ("%d", &b[i]);    for (i=1;i<n;i++) {        Dp[i][0]=max (Dp[i-1][0],dp[i-1][1]+abs (1-b[i-1]));        Dp[i][1]=max (Dp[i-1][0]+abs (b[i]-1), Dp[i-1][1]+abs (B[i]-b[i-1]));    }    printf ("%d\n", Max (dp[n-1][0],dp[n-1][1]));}

  



---restore content ends---

Maximum cost of 51nod1270 array (simple DP)

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.