1664. Ways to Make a Fair Array
package LeetCode_1664 /** * 1664. Ways to Make a Fair Array * https://leetcode.com/problems/ways-to-make-a-fair-array/ * You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. * Notice that the index of the elements may change after the removal. For example, if nums = [6,1,7,4,1]: Choosing to remove index 1 results in nums = [6,7,4,1]. Choosing to remove index 2 results in nums = [6,1,4,1]. Choosing to remove index 4 results in nums = [6,1,7,4]. An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the number of indices that you could choose such that after the removal, nums is fair. Example 1: Input: nums = [2,1,6,4] Output: 1 Explanation: Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. Example 2: Input: nums = [1,1,1] Output: 3 Explanation: You can remove any index and the remaining array is fair. Example 3: Input: nums = [1,2,3] Output: 0 Explanation: You cannot make a fair array after removing any index. Constraints: 1. 1 <= nums.length <= 105 2. 1 <= nums[i] <= 104 * */ class Solution { /* * solution: increasing and decreasing even, odd; then compare two side if equals, * Time:O(n), Space:O(1) * */ fun waysToMakeFair(nums: IntArray): Int { var even = 0 var odd = 0 for (i in nums.indices) { if (i % 2 == 0) { even += nums[i] } else { odd += nums[i] } } var even2 = 0 var odd2 = 0 var result = 0 for (i in nums.indices) { //decreasing if (i % 2 == 0) { even -= nums[i] } else { odd -= nums[i] } //compare two side if (even + odd2 == odd + even2) { result++ } //increasing if (i % 2 == 0) { even2 += nums[i] } else { odd2 += nums[i] } } return result } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)