排成一条线的硬币

来源:互联网 发布:全国二手车评估软件 编辑:程序博客网 时间:2024/05/05 16:40

题目:

面值为正数的硬币放置成一排,玩家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]));    }}
原创粉丝点击