Leetcode3026. 最大好子数组和

本文介绍了如何使用哈希表和前缀和解决LeetCode题目3026,通过查找元素x及其±k的前缀和,找到子数组和的最大值。优化方法是只存储x和其最小前缀和,减少空间复杂度。
摘要由CSDN通过智能技术生成

Every day a Leetcode

题目来源:3026. 最大好子数组和

解法1:哈希 + 前缀和

哈希表 hash = unordered_map<int, vector<long long>> 存储数组 nums 的元素 x 及其到 x 为止的前缀和 preSum。

遍历数组 nums,设当前元素为 x,前缀和为 sum:

  1. 在哈希表中寻找键 x + k,若找到,更新答案 ans = max(ans, sum + x - *min_element(it->second.begin(), it->second.end()));
  2. 在哈希表中寻找键 x - k,若找到,更新答案 ans = max(ans, sum + x - *min_element(it->second.begin(), it->second.end()));
  3. 向哈希表中插入 hash[x].push_back(sum);
  4. 更新前缀和 sum += x。

最后返回答案。

代码:

/*
 * @lc app=leetcode.cn id=3026 lang=cpp
 *
 * [3026] 最大好子数组和
 */

// @lc code=start
class Solution
{
public:
    long long maximumSubarraySum(vector<int> &nums, int k)
    {
        long long ans = LLONG_MIN, sum = 0;
        unordered_map<int, vector<long long>> hash;
        for (int &x : nums)
        {
            auto it = hash.find(x + k);
            if (it != hash.end())
                ans = max(ans, sum + x - *min_element(it->second.begin(), it->second.end()));

            it = hash.find(x - k);
            if (it != hash.end())
                ans = max(ans, sum + x - *min_element(it->second.begin(), it->second.end()));

            hash[x].push_back(sum);
            sum += x;
        }
        return ans == LLONG_MIN ? 0 : ans;
    }
};
// @lc code=end

结果:

超时。

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的元素个数。

空间复杂度:O(n),其中 n 是数组 nums 的元素个数。

优化

我们发现,哈希表中最需要存储元素 x 及其对应的最小的前缀和,这样算出来的子数组元素总和是最大的。

修改:

  1. 更新答案 ans = max(ans, sum + x - it->second);
  2. 每次还有在哈希表中查找 x,如果找不出或者当前前缀和 sum 小于 hash[x],更新 hash[x] = sum。

代码:

/*
 * @lc app=leetcode.cn id=3026 lang=cpp
 *
 * [3026] 最大好子数组和
 */

// @lc code=start
class Solution
{
public:
    long long maximumSubarraySum(vector<int> &nums, int k)
    {
        long long ans = LLONG_MIN, sum = 0;
        unordered_map<int, long long> hash;
        for (int &x : nums)
        {
            auto it = hash.find(x + k);
            if (it != hash.end())
                ans = max(ans, sum + x - it->second);

            it = hash.find(x - k);
            if (it != hash.end())
                ans = max(ans, sum + x - it->second);

            it = hash.find(x);
            if (it == hash.end() || sum < it->second)
                hash[x] = sum;
            sum += x;
        }
        return ans == LLONG_MIN ? 0 : ans;
    }
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的元素个数。

空间复杂度:O(n),其中 n 是数组 nums 的元素个数。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值