Candy Love
有N个孩子参加聚会,您已决定向这些孩子分发糖果作为回礼。子代的编号从1到N。给您一个数组A,该数组定义可以分配给任何子代的最大糖果数。可以给任何孩子使用的糖果数量有限制:
一方的集体成功由函数S给出,该函数的计算公式如下:
function S():
Array C denotes the number of candies given to each child
sum = o
for i = 2 to N:
sum = sum a abs(c[i]-[i-1])
return sum
现在,作为聚会的主持人,您想最大程度地提高聚会的成功率。因此,以使派对成功最大化的方式分配糖果。输出可获得的成功最大值。
>##Sample Input##
You will be given N denoting the number of children in party and next line will consist of N space separated integers denoting the maximum candies which can be given to any child.
>##Sample Output##
Print the maximum success value of party which can be obtained.
>##Constraints##
2 <= N <= 10^5
1 <= A[i] <= 10^9
>##Sample Input 1##
3
1 2 4
>##Sample Output 1##
3
>##Sample Input 2##
6
3 10 15 10 3 10
>##Sample Output 2##
45
>##Explanation 1##
One of the ways to get success value as 3 is giving {1,2,4} candies to children respectively.
>##Explanation 2##
One of the ways to get success value as 45 is giving {1,10,1,10,1,10} candies to children respectively.
答案 0 :(得分:0)
-为使差异的总和最大化,应将数组的每个值X更改为1或X
import java.io.*;
class Test
{
static int maximumDifferenceSum(int arr[], int N)
{
int dp[][] = new int [N][2];
for (int i = 0; i < N; i++)
dp[i][0] = dp[i][1] = 0;
for (int i = 0; i< (N - 1); i++)
{
//dp[i][0] stores the maximum value of sum using first i elements if ith array value is modified to 1
dp[i + 1][0] = Math.max(dp[i][0],
dp[i][1] + Math.abs(1 - arr[i]));
//dp[i][1] stores the maximum value of sum using first i elements if ith array value is kept as a[i]
dp[i + 1][1] = Math.max(dp[i][0] +
Math.abs(arr[i + 1] - 1),
dp[i][1] + Math.abs(arr[i + 1]
- arr[i]));
}
return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
public static void main (String[] args)
{
int arr[] = {3,10,15,10,3,10};
int N = arr.length;
// output will be 45
System.out.println( maximumDifferenceSum(arr, N));
}
}