Code: Select all
4
1 1 1 1
1 1 1 1
1 1 1 -1
1 1 1 1
Read some other threads on this problem to find the algo to use for it.
Moderator: Board moderators
Code: Select all
4
1 1 1 1
1 1 1 1
1 1 1 -1
1 1 1 1
Code: Select all
#include <iostream.h>
#include <limits.h>
void init_array2(int array[100]);
void main()
{
int N;
int i, x, array[100] = {0}, limits, col;
int in_data, sub_cumulative, max_sum;
int *table;
cin >> N;
limits = N*N;
table = new int[limits];
for (i = 0; i < limits; i++)
cin >> table[i];
max_sum = INT_MIN;
sub_cumulative = 0;
for (i = 0; i < limits; i++) {
for (x = i, col = i % N; x < limits; ) {
in_data = table[x];
array[col] = (in_data > array[col] + sub_cumulative + in_data) ?
in_data :
array[col] + sub_cumulative + in_data;
sub_cumulative = (in_data > sub_cumulative + in_data) ?
in_data:
sub_cumulative + in_data;
if (array[col] > max_sum) {
max_sum = array[col];
}
if (++x % N == 0) { /* end of row */
x += i % N; /* move to next row */
sub_cumulative = 0;
col = i % N; /* start column */
}
else
col++;
} /* end of one sub rectangle */
init_array2(array);
} /* end of otter for() */
cout << max_sum << endl;
}
void init_array2(int array[100])
{
for (int i = 0; i < 100; i++)
array[i] = 0;
}
I really, really don't think there's an easy O(N^2) algo for this algo (and by easy I mean necessitating less than a lifetime of research) . It's been an open problem for 20 years or more. This problem is known as the maximum subarray problem in the literature.CodeMaker wrote:Do you think you can solve this in O(n^2), because I thought only O(n^3) exists.have you got a profe on this O(n^2) theorem?
Code: Select all
Suppose the array is: A1,A2,A3,A4 ... An
1.MaxMax <-- 0
2. For i=1,2...n
2.1. If Ai<=0 then: goto 2. (We don't want to begin with a negative)
2.2. (Now Ai is positive, so let it be the beginning of this sub-array)
sum <-- Ai ; max <-- Ai
3.3. For j=i+1,i+2...
3.3.1. sum <-- sum+Ai
3.3.2. If sum>max then: max <-- sum
3.3.3. Else if sum<=0 then:
(this sub-array can't have max sum, so give ti up.)
3.3.3.1. If max>MaxMax then: MaxMax <-- max
3.3.3.2. goto 2.(Try to begin with another positive)