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

Question:

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).

Asked By: Nehal Birla

||

Answers:

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).

Answered By: BrownieInMotion
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.