Beingamanforever

Maximal 2D Subarray Sum

Dec 5th, 2024
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-12-05 21:34:33
  4.  **/
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  8. #define NeedForSpeed                  \
  9.     ios_base::sync_with_stdio(false); \
  10.     cin.tie(NULL);                    \
  11.     cout.tie(NULL);
  12. #define int long long
  13. #define all(x) (x).begin(), (x).end()
  14. typedef vector<int> vi;
  15. typedef vector<bool> vb;
  16. typedef vector<vi> vvi;
  17. typedef vector<pair<int, int>> vpi;
  18. #define f first
  19. #define s second
  20. #define yes cout << "YES" << endl
  21. #define no cout << "NO" << endl
  22. #define endl "\n"
  23. const int mod = 1000000007;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. vi a;
  26. int kadane(vi &a)
  27. {
  28.     int n = a.size();
  29.     int max_sum = INT_MIN;
  30.     int sum = 0;
  31.     for (int i = 0; i < n; i++)
  32.     {
  33.         sum += a[i];
  34.         max_sum = max(max_sum, sum);
  35.         if (sum < 0)
  36.         {
  37.             sum = 0;
  38.         }
  39.     }
  40.     return max_sum;
  41. }
  42. void solve()
  43. {
  44.     // maximal sum rectangle
  45.     int n;
  46.     cin >> n;
  47.     int grid[n][n];
  48.     for (int i = 0; i < n; i++)
  49.     {
  50.         for (int j = 0; j < n; j++)
  51.         {
  52.             cin >> grid[i][j];
  53.         }
  54.     }
  55.     // fix the left and move the right
  56.     a.resize(n);
  57.     int ans = INT_MIN;
  58.     for (int l = 0; l < n; l++)
  59.     {
  60.         for (int i = 0; i < n; i++)
  61.         {
  62.             // reset the array
  63.             a[i] = 0;
  64.         }
  65.         for (int r = l; r < n; r++)
  66.         {
  67.             for (int i = 0; i < n; i++)
  68.             {
  69.                 a[i] += grid[i][r];
  70.             }
  71.             ans = max(ans, kadane(a));
  72.         }
  73.     }
  74.     cout << ans << endl;
  75.     return;
  76. }
  77.  
  78. signed main()
  79. {
  80.     NeedForSpeed;
  81.     int t = 1;
  82.     // cin >> t;
  83.     while (t--)
  84.     {
  85.         solve();
  86.     }
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment