leetcode 486. Predict the Winner
来源:互联网 发布:电脑淘宝微淘在哪里找 编辑:程序博客网 时间:2024/05/22 16:39
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.Example 1:Input: [1, 5, 2]Output: FalseExplanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.Example 2:Input: [1, 5, 233, 7]Output: TrueExplanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.Note:1 <= length of the array <= 20.Any scores in the given array are non-negative integers and will not exceed 10,000,000.If the scores of both players are equal, then player 1 is still the winner.
关键是两个数组,先手收益和后手收益
采用递归的话,压栈太多,复杂度可能为指数。
采用动态规划,开辟两个二维数组,保存先手和后手收益
public class Solution { public boolean PredictTheWinner(int[] nums) { if(nums==null||nums.length==0) return false; if(nums.length==1) return true; int[][] f = new int[nums.length][nums.length]; int[][] s = new int[nums.length][nums.length]; for(int j=0; j< nums.length; j++){ f[j][j] = nums[j]; for(int i=j-1; i>=0; i--){ f[i][j] = Math.max(nums[i] + s[i+1][j], nums[j] + s[i][j-1]); s[i][j] = Math.min(f[i+1][j], f[i][j-1]); } } return f[0][nums.length-1] >= s[0][nums.length-1]; }}
阅读全文
0 0
- [LeetCode]486. Predict the Winner
- LeetCode 486. Predict the Winner
- [leetcode]486. Predict the Winner
- LeetCode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- leetcode:486. Predict the Winner
- 【Leetcode】486. Predict the Winner
- Leetcode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- LeetCode 486. Predict the Winner
- leetcode 486. Predict the Winner
- leetcode 486. Predict the Winner
- [LeetCode] 486. Predict the Winner
- Leetcode 486. Predict the Winner
- LeetCode 486.Predict the Winner
- Leetcode 486. Predict the Winner
- leetcode 486. Predict the Winner
- leetcode 486. Predict the Winner
- 仿今日头条订阅频道
- 神经网络模型之AlexNet的一些总结
- 简单的POJO属性自动包装
- JS的平凡之路--简易的图片拖拽排序
- 函数指针,指针函数,返回值为指针的函数
- leetcode 486. Predict the Winner
- html form表单提交后不刷新不跳转的实现方法------
- react最佳入门实践(1)
- jvm securerandom.source 导致的sqoop问题分析
- HDU 4857 逃生(拓扑排序 小的尽量在前)
- 一些疑问,和随心笔记
- 初识JavaScript中的基本数据类型和引用类型
- Unity3D引擎WWW资源加载和缓存(AssetBundle、Texture、Audio)
- HDU 5976 贪心+逆元