码迷,mamicode.com
首页 > 其他好文 > 详细

array / matrix subarray/submatrix sum

时间:2016-11-07 07:49:08      阅读:203      评论:0      收藏:0      [点我收藏+]

标签: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_problemhttps://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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!