Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <cstring>
- #include <climits>
- using namespace std;
- int **createArray(int, int);
- void maxSubArraySum();
- void deleteArray(int, int);
- int main()
- {
- maxSubArraySum();
- return 0;
- }
- int kadane(int *subArray, int top, int bottom, int n)
- {
- int sum = 0;
- int maxSum = INT_MIN;
- bottom = -100;
- for (int i = 0; i < n; ++i)
- {
- sum += subArray[i];
- if (sum < 0)
- sum = 0;
- else if (sum > maxSum)
- {
- maxSum = sum;
- bottom = i;
- }
- }
- if (bottom >= 0) // to check if (sum>maxSum) condition is met
- return maxSum;
- maxSum = subArray[0]; // to check whether array contains only negative numbers
- for (int j = 0; j < n; ++j)
- {
- if (subArray[j] > maxSum)
- maxSum = subArray[j];
- else
- maxSum = 0;
- }
- return maxSum;
- }
- void maxSubArraySum()
- {
- int z, n, m;
- int top, right, bottom, left, sum;
- int finalTop, finalRight, finalBottom, finalLeft, maxSum = INT_MIN; // final output
- std::cout << "Enter number of sets:" << std::endl;
- std::cin >> z;
- for (int i = 0; i < z; ++i)
- {
- cout << "Enter columns and rows" << endl;
- cin >> n >> m;
- int **t = createArray(n, m);
- for (left = 0; left < m; ++left)
- {
- int subArray[n] = {0};
- for (right = left; right < m; ++right)
- {
- for (int j = 0; j < n; ++j) // extracting single columns from t array
- subArray[j] += t[j][right];
- sum = kadane(subArray, top, bottom, n);
- if (sum > maxSum)
- maxSum = sum;
- }
- }
- cout << "Max sum is: " << maxSum << endl;
- }
- }
- int **createArray(int n, int m)
- {
- int **tab = nullptr;
- if ((n >= 1 && n <= 100) && (m >= 1 && m <= 100))
- {
- try
- {
- tab = new int *[n];
- }
- catch (std::bad_alloc &b)
- {
- std::cout << "bad alloc: " << b.what() << std::endl;
- }
- for (int i = 0; i < n; ++i)
- try
- {
- tab[i] = new int[m];
- }
- catch (std::bad_alloc &b)
- {
- std::cout << "bad alloc: " << b.what() << std::endl;
- }
- std::cout << "Enter array elements: " << std::endl;
- for (int i = 0; i < n; ++i)
- for (int j = 0; j < m; ++j)
- std::cin >> tab[i][j];
- return tab;
- }
- else
- std::cout << "tu bedzie zakonczenie programu" << std::endl;
- }
- void f_deleteArray(int **t, int m)
- {
- for (int i = 0; i < m; ++i)
- delete[] t[i];
- delete[] t;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement