Skip to content

Commit fd6fc6f

Browse files
committed
2862. Maximum Element-Sum of a Complete Subset of Indices
1 parent c8b30b4 commit fd6fc6f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

2501-3000/2862. Maximum Element-Sum of a Complete Subset of Indices.swift

+19
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,27 @@ class Solution {
33
// Solution by Sergey Leschev
44
// 2862. Maximum Element-Sum of a Complete Subset of Indices
55

6+
// Intuition
7+
// A set of numbers is considered complete if the product of every pair of its elements is a perfect square.
8+
// In this problem, we are given an array of integers and are tasked with finding the maximum possible sum of elements in a complete subset of indices.
9+
10+
// Approach
11+
// To tackle this problem, we start by determining the "key" for each index in the array.
12+
// This key is found by iteratively dividing the index by all possible square numbers until we can no longer do so.
13+
// For example, the key of index 1 is 1, the key of index 18 is 2, and the key of index 24 is 6. In a complete set, all indices share the same key.
14+
15+
// We maintain a dictionary count to keep track of the sum of elements associated with each key.
16+
// For each index i in the array, we find its key x, accumulate A[i] to count[x], and update our result res as the maximum between its current value and count[x].
17+
// Finally, we return res as our result, which represents the maximum possible sum of a complete subset of indices in the given array.
18+
19+
// By using this approach, we can efficiently determine the maximum element-sum for a complete subset of indices,
20+
// ensuring the product of their elements is always a perfect square.
21+
622
// Time complexity: O(n)
723
// Space complexity: O(n)
24+
// The process to determine each key has a time complexity of O(sqrt(n)).
25+
// However, by precalculating all the keys, the final solution becomes O(n).
26+
// In fact, the complexity can be simplified to O(n) due to the sum of a convergent series (1 + 1/4 + 1/9 + ...).
827

928
func maximumSum(_ nums: [Int]) -> Int {
1029
var count = [Int: Int]()

0 commit comments

Comments
 (0)