
Sponsored
Sponsored
This approach involves calculating the prefix sum for every column and iterating over pairs of row indices to form vertical strips. The idea is derived from simplifying the multidimensional problem to a manageable form by transforming it into a 1D problem with the help of prefix sums and leveraging subarray sum computation techniques.
Time Complexity: O(n^2 * m log m), where m = num of rows and n = num of columns. Space Complexity: O(m) for storing row sums.
1#include <vector>
2#include <set>
3
4using namespace std;
5
6int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
7 if (matrix.empty()) return 0;
8 int maxSum = INT_MIN, rows = matrix.size(), cols = matrix[0].size();
9
10 for (int left = 0; left < cols; ++left) {
11 vector<int> rowSum(rows, 0);
12 for (int right = left; right < cols; ++right) {
13 for (int r = 0; r < rows; ++r) {
14 rowSum[r] += matrix[r][right];
15 }
16 maxSum = max(maxSum, maxSumNoLargerThanK(rowSum, k));
17 }
18 }
19 return maxSum;
20}
21
22int maxSumNoLargerThanK(vector<int>& nums, int k) {
23 set<int> accuSet;
24 accuSet.insert(0);
25 int sum = 0, maxSum = INT_MIN;
26 for (int num : nums) {
27 sum += num;
28 auto it = accuSet.lower_bound(sum - k);
29 if (it != accuSet.end()) maxSum = max(maxSum, sum - *it);
30 accuSet.insert(sum);
31 }
32 return maxSum;
33}In the C++ version, we iterate over pairs of columns and calculate running sums in the form of rowSum. For each set of rowSum, we identify the max subarray no larger than k using a set to maintain seen cumulative sums and binary search for possible subarrays starting indices using std::set.lower_bound.
This approach uses recursion to solve the problem by breaking it down into smaller subproblems and storing the results of these subproblems to avoid redundant calculations. Hence, it combines recursion with memoization.
Time Complexity: O(n)
Space Complexity: O(n) due to the memoization array
1
This approach solves the problem iteratively, preventing the overhead of recursive function calls. It constructs a solution bottom-up and is generally more space-efficient.
Time Complexity: O(n)
Space Complexity: O(1)
1using System;
class Program {
static int Fib(int n) {
if (n <= 1) return n;
int a = 0, b = 1, c;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
static void Main() {
int n = 10; // Example
Console.WriteLine(Fib(n));
}
}The C solution initializes a memo array to store intermediate results. The solve function checks if the value is already computed to avoid recalculating it, and recursively calculates values as needed.
The C# iterative solution helps utilize minimal space by merely updating variables that track the required Fibonacci numbers.