标签:tab nlogn prefix org new mini upper als https
Maximal Subarray Sum : O(n) scan-and-update dynamic programming,https://en.wikipedia.org/wiki/Maximum_subarray_problem, https://leetcode.com/problems/maximum-subarray
Shortest Subarray Sum Equals K : prefix-sum + sort + hash-table: O(nlogn) time, O(n) storage; https://leetcode.com/problems/minimum-size-subarray-sum/
if it‘s positive only, sliding window can also work.
Longest Subarray Sum Equals K : prefix-sum + sort + hash-table: O(n) time, O(n) storage, https://leetcode.com/problems/maximum-size-subarray-sum-equals-k
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int sum = 0, res = 0;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (sum == k) res = i + 1;
else if (m.count(sum - k)) res = max(res, i - m[sum - k]);
if (!m.count(sum)) m[sum] = i;
}
return res;
}
};
Longest Subarray Sum At Least (At Most) K : change hash-table to a map, and lower_bound / upper_bound : prefix-sum + sort + BST : O(nlogn) time, O(n) storage; https://www.quora.com/Given-an-array-of-integers-A-and-an-integer-k-find-a-subarray-that-contains-the-largest-sum-subject-to-a-constraint-that-the-sum-is-less-than-k
int best_cumulative_sum(int ar[],int N,int K)
{
set<int> cumset;
cumset.insert(0);
int best=0,cum=0;
for(int i=0;i<N;i++)
{
cum+=ar[i];
set<int>::iterator sit=cumset.upper_bound(cum-K);
if(sit!=cumset.end())best=max(best,cum-*sit);
cumset.insert(cum);
}
return best;
}
Rectangle: sum all possible [i, j] columns, and reduce the case to 1-D, in total O(n^2) * 1-D case.
Max Sum of Rectangle No Larger Than K : sum all possible [i, j] columns together, reduce to 1-D case, in total n^2*nlogn. https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/
array / matrix subarray/submatrix sum
标签:tab nlogn prefix org new mini upper als https
原文地址:http://www.cnblogs.com/qsort/p/6037053.html