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。

相关推荐
圣保罗的大教堂8 分钟前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
longlongzihan13 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince18 小时前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂18 小时前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
All for pursuit.1 天前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
Tisfy1 天前
LeetCode 0678.有效的括号字符串:O(n)+O(1)一次遍历
算法·leetcode·字符串·题解·贪心·括号匹配
Navigator_Z2 天前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木2 天前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.2 天前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode