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。

相关推荐
文丑颜不良啊2 小时前
LeetCode876~900题目解析
java·leetcode
木井巳11 小时前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
晒太羊的猫12 小时前
hot100子串
java·算法·leetcode
海清河晏11113 小时前
加油站问题
数据结构·算法·leetcode
Nuanyt14 小时前
LeetCode Hot 100 · 双指针 3 题 Java
java·笔记·算法·leetcode·双指针
文丑颜不良啊15 小时前
LeetCode851~875题目解析
java·leetcode
Navigator_Z16 小时前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
?abc!1 天前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
hold?fish:palm1 天前
40 二叉树的直径
c++·leetcode
guo_wen_qiang1 天前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节