#1338 : A Game
描述
Little Hi and Little Ho are playing a game. There is an integer array in front of them. They take turns (Little Ho goes first) to select a number from either the beginning or the end of the array. The number will be added to the selecter's score and then be removed from the array.
Given the array what is the maximum score Little Ho can get? Note that Little Hi is smart and he always uses the optimal strategy.
输入
The first line contains an integer N denoting the length of the array. (1 ≤ N ≤ 1000)
The second line contains N integers A1, A2, ... AN, denoting the array. (-1000 ≤ Ai ≤ 1000)
输出
Output the maximum score Little Ho can get.
样例输入
4
-1 0 100 2
样例输出
99
解题思路:本来笔者采用贪心算法解决,可发现当前最优并不能保证整体最优,因而放弃贪心算法的思想,转而动态规划的思想
#include<stdio.h>
#include<iostream>
using namespace std;
int n;//数组长度
int nums[1010],sum[1010];
int dp[1010][1010];//dp[i][j]表示当前以i开头,以j为长度的数组中最大和
int main()
{
scanf("%d", &n);
for(int i=1;i<=n;++i){
scanf("%d",&nums[i]);
sum[i]=sum[i-1]+nums[i];
dp[i][1]=nums[i];//初始化 dp[i][1]表示以i开始,1长度数组的最大和为nums[i]
}
for(int j=2;j<=n;++j)//从长度为2开始
for(int i=1;i<=n;++i)
if (i+j-1<=n)
dp[i][j]=max(sum[i+j-1]-sum[i-1]-dp[i+1][j-1],sum[i+j-1]-sum[i-1]-dp[i][j-1]);//动态规划状态转移
printf("%d\n",dp[1][n]);
return 0;
}