ProgrammingVery hard
Which approach finds the maximum sum rectangle in an n x n int matrix with n = 500 within a second in C?
- A. Try every rectangle with four nested loops, about 6 x 10^10 steps
- B. Fix the top and bottom rows and run Kadane's algorithm on column sums, about n^3 = 1.25 x 10^8 steps
- C. Try every rectangle with two loops and sum each in O(n), about n^4 steps
- D. Sort all rectangles by sum, which is far more than n^4 work
Correct answer: B. Fix the top and bottom rows and run Kadane's algorithm on column sums, about n^3 = 1.25 x 10^8 steps
Fixing the row pair and applying Kadane to column sums gives O(n^3). Four nested loops cost about n^4 / 4, which is about 1.6 x 10^10 for n = 500.
More C Programming questions
- int a[2][3]; with two rows and three columns in a variable-length array, what is sizeof(a) on a platform with 4-byte int?
- char names[3][6] = {"ab", "cde"}; What is sizeof names[1]?
- Which statement about memset(a, 0, sizeof a) for a 2D int array a[4][5] is correct?
- int a[3][4]; int p = &a[0][0]; Which expression refers to a[2][1]?
- On a machine with 4-byte int, what does sizeof(r) give when int (r)[3] is a pointer to a row of three ints?
- Three rows are each malloc'd separately, and their pointers are stored in an array rowp[3]. Which cleanup order is correct?