Leetcode Coins in a line

There are n coins in a line. (Assume n is even). Two players take turns to take a coin
from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
1. Would you rather go first or second? Does it matter?
2. Assume that you go first, describe an algorithm to compute the maximum amount of money you can win.


[code]

import java.util.*;

public class Solution {
    public static void main(String[] args)
    {
        int []array={3,2,2,3,1,2};
        Solution s=new Solution(array);
        s.coin(array, 0, array.length-1);
        s.print();
    }
    int dp[][];
    Solution(int[] array)
    {
        dp=new int[array.length][array.length];
        for(int i=0;i<dp.length;i++)Arrays.fill(dp[i], -1);
    }
    void print()
    {
        for(int i=0;i<dp.length;i++)
        {
            for(int j=i;j<dp[0].length;j++)System.out.print(dp[i][j]+"\t");
            System.out.println();
        }
    }
    int coin(int[] array, int start, int end)
    {
        if(start>end)return 0;
        if( dp[start][end]==-1 )
        {
            int p1 = array[start] + Math.min( coin( array, start+2, end ) ,  coin( array, start+1, end-1 ) );
            int p2 = array[end] + Math.min( coin( array, start+1, end-1 ) ,  coin( array, start, end-2 ) );
            dp[start][end] = Math.max( p1, p2 );
        }
        return dp[start][end];
    }

}

[Thoughts]
这里的解法是以对手很聪明为前提:
p( i, j ) = max ( A[i] + min ( p(i+2, j), p(i+1, j-1) ), A[j] + min( p(i, j-2), p(i+1, j-1) ) ).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值