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

- i<j<k (where i j and k are indexes)
- A[i]<A[j]<A[k]
- 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(n^{3}). I need to find the solution so that it is less than o(n^{3}).

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