排成一条线的硬币

题目:

面值为正数的硬币放置成一排,玩家1和玩家2轮流拿走硬币,
规定每个玩家在拿硬币时,只能拿走最左或最右的硬币。
每个玩家获得的分数是各自拿走硬币的总和。
因为玩家1先拿硬币,所以如果最后两人获得分数一样则玩家2获胜;否则分数大的获胜
给定一个数组arr,表示硬币的面值和排列状况,请返回最终获胜者的分数。
输入例子:
4
8 7 5 3
输出例子:13

用递归

public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int a[]=new int[n];
        int sum=0;
        for(int i=0;i<n;i++){
            a[i]=sc.nextInt();
            sum+=a[i];
        }
        sc.close();
        int first=dfs(a,0,n-1);
        int second=sum-first;
        System.out.println(Math.max(first,second));
    }
    public static int dfs(int[] arr,int start,int end){//线的头和尾
        if(start==end){//如果只剩一枚硬币,直接拿走
            return arr[start];
        }
        else if(start>end){//无效
            return 0;
        }
        else{
            return Math.max(//选对自己最有利的
                    arr[start]+Math.min(//取头,对方一定会选对对方最有利的,所有是min
                            dfs(arr,start+1,end-1),//对方取尾
                            dfs(arr,start+2,end))//对方取头
                            , arr[end]+Math.min(//取尾
                                    dfs(arr,start,end-2),//对方取尾
                                    dfs(arr,start+1,end-1)));//对方取头
        }
    }
}

或者用动态规划:

public class 排成一条线的硬币 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++){
            a[i]=sc.nextInt();
        }
        sc.close();
        int fast[][]=new int[n][n];
        int slow[][]=new int[n][n];
        for(int i=n-1;i>=0;i--){
            fast[i][i]=a[i];
            for(int j=i+1;j<n;j++){
                fast[i][j]=Math.max(a[i]+slow[i+1][j],a[j]+slow[i][j-1]);
                slow[i][j]=Math.min(fast[i+1][j],fast[i][j-1]);
            }
        }
        System.out.println(Math.max(fast[0][n-1],slow[0][n-1]));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值