3381. Maximum Subarray Sum With Length Divisible by K
You are given an array of integers nums
and an integer k
.
Return the maximum sum of a non-empty subarray of nums
, such that the size of the subarray is divisible by k
.
A subarray is a contiguous non-empty sequence of elements within an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: long long maxSubarraySum(vector<int>& nums, int k) { long long res = LLONG_MIN; unordered_map<long long, long long> mi; for(long long i = 0, sum = 0; i <= nums.size(); i++) { if(!mi.count(i%k)) mi[i] = sum; else { res = max(res, sum - mi[i%k]); mi[i%k] = min(mi[i%k], sum); } if(i != nums.size()) sum += nums[i]; } return res; } };
|