Day 16:3040. 相同分数的最大操作数目II
Leetcode 相同分数的最大操作数目II
给你一个整数数组 nums ,如果 nums 至少 包含 2 个元素,你可以执行以下操作中的 任意 一个:
- 选择 nums 中最前面两个元素并且删除它们。
- 选择 nums 中最后两个元素并且删除它们。
- 选择 nums 中第一个和最后一个元素并且删除它们。
一次操作的 分数 是被删除元素的和。
在确保** 所有操作分数相同** 的前提下,请你求出 最多 能进行多少次操作。
请你返回按照上述要求 最多 可以进行的操作次数。
可以理解为一颗三叉树,其中一棵子树选择数组前两个元素,一棵选择第一个和最后的一个元素,最后一棵子树选择最后两个元素。
完整代码
class Solution { public int maxOperations(int[] nums) { int n = nums.length; if (n == 2) return 1; int res = maxOperation2(nums, nums[0] + nums[1], 2, n - 1) + 1; if (res == nums.length / 2) return res; res = Math.max(res, maxOperation2(nums, nums[n - 1] + nums[n - 2], 0, n - 3) + 1); if (res == nums.length / 2) return res; res = Math.max(res, maxOperation2(nums, nums[0] + nums[n - 1], 1, n - 2) + 1); return res; } public int maxOperation2(int[] nums, int sum, int start, int end) { int res = 0; if (end - start == 1 && nums[start] + nums[end] == sum) res = 1; else if (end - start > 1) { // 前两个 if ((nums[start] + nums[start + 1]) == sum) { res = Math.max(res, maxOperation2(nums, sum, start + 2, end) + 1); } if (res == nums.length / 2) return res; // 最后两个 if ((nums[end] + nums[end - 1]) == sum) { res = Math.max(res, maxOperation2(nums, sum, start, end - 2) + 1); } if (res == nums.length / 2) return res; // 第一个和最后一个 if ((nums[start] + nums[end]) == sum) { res = Math.max(res, maxOperation2(nums, sum, start + 1, end - 1) + 1); } } return res; } }
以上 maxOperation2()函数的调用许多传入了相同的参数,因此浪费了大量时间,最后会超出时间限制。
建一个二维数组保存范围结果。class Solution { int[] nums; int[][] memo; public int maxOperations(int[] nums) { int n = nums.length; this.nums = nums; this.memo = new int[n][n]; int res = 0; res = Math.max(res, helper(0, n - 1, nums[0] + nums[n - 1])); res = Math.max(res, helper(0, n - 1, nums[0] + nums[1])); res = Math.max(res, helper(0, n - 1, nums[n - 2] + nums[n - 1])); return res; } public int helper(int i, int j, int target) { for (int k = 0; k = j) { return 0; } if (memo[i][j] != -1) { return memo[i][j]; } int ans = 0; if (nums[i] + nums[i + 1] == target) { ans = Math.max(ans, dfs(i + 2, j, target) + 1); } if (nums[j - 1] + nums[j] == target) { ans = Math.max(ans, dfs(i, j - 2, target) + 1); } if (nums[i] + nums[j] == target) { ans = Math.max(ans, dfs(i + 1, j - 1, target) + 1); } memo[i][j] = ans; return ans; } }
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

