Leetcode 2862. Maximum Element-Sum of a Complete Subset of Indices

  • [Leetcode 2862. Maximum Element-Sum of a Complete Subset of Indices](#Leetcode 2862. Maximum Element-Sum of a Complete Subset of Indices)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的核心在于想明白一点:

  • 要使得子序列当中任意两个数之积均为平方数,那么子序列当中的所有数必然都是一系列平方数的某一个公倍数。

因此,我们只需要不超过数组长度 n n n的所有平方数,然后分别将其扩展倍数即可。

而对于扩展倍数之后依然有效的平方数,我们同样可以通过二分法进行优化寻找。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:    
    def maximumSum(self, nums: List[int]) -> int:
        n = len(nums)

        completes = [i*i for i in range(1, int(sqrt(n) + 2)) if i * i <= n]
        res = max(max(nums), sum([nums[i-1] for i in completes]))
        for p in range(1, n+1):
            if p > n:
                break
            if completes[-1] * p > n:
                i, j = 0, len(completes)-1
                while j-i>1:
                    m = (i+j)//2
                    if completes[m] * p > n:
                        j = m
                    else:
                        i = m
            else:
                j = len(completes)
            if j == 1:
                break
            s = sum([nums[p*i-1] for i in completes[:j]])
            res = max(res, s)
        return res

提交代码评测得到:耗时290ms,占用内存18.1MB。

相关推荐
琢磨先生David8 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll8 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐8 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶8 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER8 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了8 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333338 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录8 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1238 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode