
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum Size Subarray Sum Equals k in C++
Suppose we have an array called nums and a target value k, we have to find the maximum length of a subarray that sums to k. If there is not present any, return 0 instead.
So, if the input is like nums = [1, -1, 5, -2, 3], k = 3, then the output will be 4, as the subarray [1, - 1, 5, -2] sums to 3 and is the longest.
To solve this, we will follow these steps −
ret := 0
Define one map m
n := size of nums
temp := 0, m[0] := -1
for initialize i := 0, when i < n, update (increase i by 1), do −
temp := temp + nums[i]
if (temp - k) is in m, then −
ret := maximum of ret and i - m[temp - k]
if temp is not in m, then −
m[temp] := i
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxSubArrayLen(vector<int<& nums, int k) { int ret = 0; unordered_map <int, int> m; int n = nums.size(); int temp = 0; m[0] = -1; for(int i = 0; i < n; i++){ temp += nums[i]; if(m.count(temp - k)){ ret = max(ret, i - m[temp - k]); } if(!m.count(temp)){ m[temp] = i; } } return ret; } }; main(){ Solution ob; vector<int< v = {1,-1,5,-2,3}; cout << (ob.maxSubArrayLen(v, 3)); }
Input
[1,-1,5,-2,3], 3
Output
4
- Related Articles
- Subarray Sum Equals K in C++
- Find maximum (or minimum) sum of a subarray of size k in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++ program
- Maximum Unique Element in every subarray of size K in c++
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Minimum Size Subarray Sum in C++
- Maximum Sum Circular Subarray in C++
- Maximum sum bitonic subarray in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Maximum subarray sum in array formed by repeating the given array k times in C++
- Maximum subarray sum modulo m in C++
- Maximum circular subarray sum in C++\n
- Maximum contiguous sum of subarray in JavaScript
- Find maximum average subarray of k length in C++

Advertisements