---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)