Can anyone please check and let me know why this code is giving wrong answer?


#1
 public class Solution {
  public int solve(int[] A) {
    int n = A.length;
    long ans = 0;
    TreeSet<Integer> set = new TreeSet();
    int[] right = new int[n];
    int[] left = new int[n];
    Arrays.fill(right, -1);
    Arrays.fill(left, -1);
    for (int i = n - 1; i >= 0; i--) {
        if (set.isEmpty())
            set.add(A[i]);
        else {
            if (A[i] < set.last()) {
                right[i] = set.last();
            }
            set.add(A[i]);
        }
    }
    set.clear();
    for (int i = 0; i < n; i++) {
        if (set.isEmpty())
            set.add(A[i]);
        else {
            if (set.floor(A[i]) != null && set.floor(A[i]) < A[i]) {
                left[i] = set.floor(A[i]);
            }
            set.add(A[i]);
        }
    }
    for (int i = 0; i < n; i++) {
        if (left[i] != -1 && right[i] != -1) {
            long temp = 0;
            temp = left[i] + A[i] + right[i];
            ans = Math.max(ans,temp);
        }
    }
    return (int) ans;
   }
}