Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find triplets from an array such that i<j<k, A[i]<A[j]<A[k] and B[i]+B[j]+B[k] is maximum

There are two arrays A and B. I need to find sum of triplet in B with three conditions :-

  1. i<j<k (where i j and k are indexes)
  2. A[i]<A[j]<A[k]
  3. B[i]+B[j]+B[k] is maximum

I have tried this question but I can not find a way to optimize it. The time complexity that I am getting is o(n3). I need to find the solution so that it is less than o(n3).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A straightforward and slightly faster solution runs in O(n ^ 2). For each "middle" index j, find i such that A[i] < A[j] maximizing B[i], and find k such that A[j] < A[k] maximizing B[k]. These can both be found in one pass over possible indices.

It should be possible to speed this up more by preprocessing the input arrays. As it stands, this solution is still better than O(n ^ 3).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading