Max Sum of Rectangle No Larger Than K

對於一維數組求最大的和並且不大於K

Array

  1. 對於二維數組,轉化爲一維的迭代

這裏寫圖片描述

代碼:

class Solution {
public:
    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
        if (matrix.empty())
            return 0;
        int row = matrix.size();
        int col = matrix[0].size();
        int res = numeric_limits<int>::min();
        for (int l = 0; l < col; l++) {
            vector<int>sums(row, 0);
            for (int r = l; r < col; ++r) {
                for (int i = 0; i < row; ++i) {
                    sums[i] += matrix[i][r];
                }

                //Find the max subarray no more than k
                set<int> accuSet;
                accuSet.insert(0);
                int curSum = 0, CurMax = numeric_limits<int>::min();
                for (int sum : sums) {
                    curSum += sum;
                    set<int>::iterator it = accuSet.lower_bound(curSum - k);
                    if (it != accuSet.end())
                        CurMax = max(CurMax, curSum - *it);
                    accuSet.insert(curSum);

                }
                res = max(res, CurMax);
            }
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章