Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5376dce

Browse files
committed
Add solution #1664
1 parent 029a8f6 commit 5376dce

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,459 LeetCode solutions in JavaScript
1+
# 1,460 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1282,6 +1282,7 @@
12821282
1659|[Maximize Grid Happiness](./solutions/1659-maximize-grid-happiness.js)|Hard|
12831283
1662|[Check If Two String Arrays are Equivalent](./solutions/1662-check-if-two-string-arrays-are-equivalent.js)|Easy|
12841284
1663|[Smallest String With A Given Numeric Value](./solutions/1663-smallest-string-with-a-given-numeric-value.js)|Medium|
1285+
1664|[Ways to Make a Fair Array](./solutions/1664-ways-to-make-a-fair-array.js)|Medium|
12851286
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
12861287
1669|[Merge In Between Linked Lists](./solutions/1669-merge-in-between-linked-lists.js)|Medium|
12871288
1672|[Richest Customer Wealth](./solutions/1672-richest-customer-wealth.js)|Easy|
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 1664. Ways to Make a Fair Array
3+
* https://leetcode.com/problems/ways-to-make-a-fair-array/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums. You can choose exactly one index (0-indexed) and remove
7+
* the element. Notice that the index of the elements may change after the removal.
8+
*
9+
* For example, if nums = [6,1,7,4,1]:
10+
* - Choosing to remove index 1 results in nums = [6,7,4,1].
11+
* - Choosing to remove index 2 results in nums = [6,1,4,1].
12+
* - Choosing to remove index 4 results in nums = [6,1,7,4].
13+
*
14+
* An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.
15+
*
16+
* Return the number of indices that you could choose such that after the removal, nums is fair.
17+
*/
18+
19+
/**
20+
* @param {number[]} nums
21+
* @return {number}
22+
*/
23+
var waysToMakeFair = function(nums) {
24+
let evenSum = 0;
25+
let oddSum = 0;
26+
let result = 0;
27+
28+
for (let i = 0; i < nums.length; i++) {
29+
if (i % 2 === 0) evenSum += nums[i];
30+
else oddSum += nums[i];
31+
}
32+
33+
let currentEven = 0;
34+
let currentOdd = 0;
35+
36+
for (let i = 0; i < nums.length; i++) {
37+
if (i % 2 === 0) {
38+
evenSum -= nums[i];
39+
if (currentEven + oddSum === currentOdd + evenSum) result++;
40+
currentEven += nums[i];
41+
} else {
42+
oddSum -= nums[i];
43+
if (currentEven + oddSum === currentOdd + evenSum) result++;
44+
currentOdd += nums[i];
45+
}
46+
}
47+
48+
return result;
49+
};

0 commit comments

Comments
 (0)