Skip to content

Commit e9cf7ab

Browse files
committedMar 11, 2025
Add solution #698
1 parent f7ccc12 commit e9cf7ab

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@
527527
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
528528
696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy|
529529
697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy|
530+
698|[Partition to K Equal Sum Subsets](./0698-partition-to-k-equal-sum-subsets.js)|Medium|
530531
700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy|
531532
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
532533
703|[Kth Largest Element in a Stream](./0703-kth-largest-element-in-a-stream.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 698. Partition to K Equal Sum Subsets
3+
* https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums and an integer k, return true if it is possible to divide this
7+
* array into k non-empty subsets whose sums are all equal.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @param {number} k
13+
* @return {boolean}
14+
*/
15+
var canPartitionKSubsets = function(nums, k) {
16+
const sum = nums.reduce((a, b) => a + b);
17+
if (sum % k !== 0) {
18+
return false;
19+
}
20+
21+
const target = sum / k;
22+
nums.sort((a, b) => b - a);
23+
if (nums[0] > target) {
24+
return false;
25+
}
26+
27+
const used = new Array(nums.length).fill(false);
28+
return backtrack(0, 0, 0);
29+
30+
function backtrack(index, count, updatedSum) {
31+
if (count === k) return true;
32+
if (updatedSum === target) return backtrack(0, count + 1, 0);
33+
if (updatedSum > target) return false;
34+
35+
for (let i = index; i < nums.length; i++) {
36+
if (!used[i]) {
37+
used[i] = true;
38+
if (backtrack(i + 1, count, updatedSum + nums[i])) return true;
39+
used[i] = false;
40+
if (updatedSum === 0) break;
41+
}
42+
}
43+
return false;
44+
}
45+
};

0 commit comments

Comments
 (0)
Please sign in to comment.