力扣3026.最大好子数组和

力扣3026.最大好子数组和

  • 一次遍历

    • 求前缀和的同时 哈希表key为元素值 value为前缀和
    • 始终保证cnt[key]的前缀和最小
cpp 复制代码
  class Solution {
  public:
      long long maximumSubarraySum(vector<int>& nums, int k) {
          long long res = LLONG_MIN , sum = 0;
          unordered_map<int,long long> min_s;
          for(int x : nums)
          {
              //找x + k的位置
              auto it = min_s.find(x + k);
              if(it != min_s.end())
                  res = max(res,sum + x - it->second);
              //找x - k的位置
              it = min_s.find(x - k);
              if(it != min_s.end())
                  res = max(res,sum + x - it->second);
              //找x的位置
              it = min_s.find(x);
              if(it == min_s.end() || sum < it->second)
                  min_s[x] = sum;
              //求当前遍历过元素的和
              sum += x;
          }
          return res == LLONG_MIN ? 0 : res;
      }
  };
相关推荐
近津薪荼3 分钟前
优选算法——双指针6(单调性)
c++·学习·算法
向哆哆35 分钟前
画栈 · 跨端画师接稿平台:基于 Flutter × OpenHarmony 的整体设计与数据结构解析
数据结构·flutter·开源·鸿蒙·openharmony·开源鸿蒙
helloworldandy35 分钟前
高性能图像处理库
开发语言·c++·算法
2401_8365631837 分钟前
C++中的枚举类高级用法
开发语言·c++·算法
bantinghy40 分钟前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
chao1898441 小时前
矢量拟合算法在网络参数有理式拟合中的应用
开发语言·算法
代码无bug抓狂人1 小时前
动态规划(附带入门例题)
c语言·算法·动态规划
weixin_445402301 小时前
C++中的命令模式变体
开发语言·c++·算法
季明洵1 小时前
C语言实现顺序表
数据结构·算法·c·顺序表
Hgfdsaqwr1 小时前
实时控制系统优化
开发语言·c++·算法