2874. Maximum Value of an Ordered Triplet II

Problem Statement

You are given a 0-indexed integer array nums.

Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all such triplets have a negative value, return 0.

The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].

Example 1:

Input: nums = [12,6,1,2,7]
Output: 77
Explanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.
It can be shown that there are no ordered triplets of indices with a value greater than 77. 

Example 2:

Input: nums = [1,10,3,4,19]
Output: 133
Explanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.
It can be shown that there are no ordered triplets of indices with a value greater than 133.

Example 3:

Input: nums = [1,2,3]
Output: 0
Explanation: The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0.

Constraints:

  • 3 <= nums.length <= 105

  • 1 <= nums[i] <= 106

Intuition

Approach:
Better

At each element, Go Left and also Right to find the Max values
As (i - j) * k
Bascially we are iterating at j to find left(i) and Right(k)

Optimal:
Save the prefix_max and suffix_max at each step to avoid the extra loop

https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-ii/description/

Approach 1:

C++
class Solution {
public:
    long long maximumTripletValue(vector<int>& v) {
        int n=v.size();
        long long ans=0;
        vector<int>l(n,0);
        vector<int>r(n,0);
        int s=v[0];
        for(int i=1;i<n;i++)
        {
            l[i]=s;
            s=max(s,v[i]);
        }
        s=v[n-1];
        for(int i=n-2;i>=0;i--)
        {
            r[i]=s;
            s=max(s,v[i]);
        }
        for(int i=1;i<n-1;i++)
        {
            long long k=(long long)(l[i]-v[i])*r[i];
            ans=max(ans,k);
        }
        return ans;
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated