Leetcode: Maximum Size Subarray Sum Equals k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. Example 1: Given nums = [1, -1, 5, -2, 3], k = 3, return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest) Example 2: Given nums = [-2, -1, 2, 1], k = 1, return 2. (because the subarray [-1, 2] sums to 1 and is the longest) Follow Up: Can you do it in O(n) time?
Like the other subarray sum problems Lintcode: Subarray Sum closest
Use a HashMap to keep track of the sum from index 0 to index i, use it as the key, and use the current index as the value
build the hashmap: scan from left to write, if the current sum does not exist in the hashmap, put it in. If the current sum does exist in Hashmap, do not replace or add to the older value, simply do not update. Because this value might be the left index of our subarray in later comparison. We are looking for the longest subarray so we want the left index to be the smaller the better.
Every time we read a number in the array, we check to see if map.containsKey(num-k), if yes, try to update the maxLen.
1 public class Solution { 2 public int maxSubArrayLen(int[] nums, int k) { 3 if (nums==null || nums.length==0) return 0; 4 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 5 map.put(0, -1); 6 int sum = 0; 7 int maxLen = Integer.MIN_VALUE; 8 for (int i=0; i<nums.length; i++) { 9 sum += nums[i]; 10 if (!map.containsKey(sum)) { 11 map.put(sum, i); 12 } 13 if (map.containsKey(sum-k)) { 14 int index = map.get(sum-k); 15 maxLen = Math.max(maxLen, i-index); 16 } 17 } 18 return maxLen==Integer.MIN_VALUE? 0 : maxLen; 19 } 20 }
分类:
Leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架