$A$ is a $m*n$ matrix
$B$ is an $n*n$ matrix

I want to return matrix C of size m*n such that:
$C_{ij} = \sum_{k=1}^{n} max(0, a_{ij} - b_{jk}) $

In pseudocode it could be like below

for i = 1 to m:
   for j = 1 to n:
      C[i,j] = 0
      for k = 1 to n:
         C[i,j] += max(0, a[i,j] - b[j,k])

this runs on $O(m*n^2)$ but it is possible to lower that.

  • 1
    $\begingroup$ If you are not familiar with "divide and conquer" algorithms then you should learn about them first. Myself, the idea that "divide and conquer" might be useful would have never occurred to me. $\endgroup$
    – gnasher729
    Sep 28, 2022 at 9:13

1 Answer 1


We can note that to compute $C_{ij}$, it is enough to know the sum, and the count of $\{b_{jk}\}_{k=1}^n$ such that $b_{jk} < a_{ij}$. This can be done after a simple preprocessing and the final time complexity will be $O(mn\log{n})$


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.