Problem 2873

Abstract / Summary

Given three integers, find the largest possible value that can be the third number in a non-decreasing sequence using all three numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2873.py

class Solution:
    def maximumTripletValue(self, nums: List[int]) -> int:
        result = 0
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                for k in range(j + 1, len(nums)):
                    value  = (nums[i] - nums[j]) * nums[k]
                    result = max(result, value)
        return result
9 lines | 363 bytes | submitted December 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method maximumTripletValue. The method receives a list of integers and computes the maximum value obtainable from any ordered triplet (i, j, k) where i < j < k. The value for a specific triplet is calculated as (nums[i] - nums[j]) * nums[k]. The algorithm explores every possible combination of three indices, keeps track of the greatest computed value, and returns it.

Key Steps

The core logic proceeds through three nested loops, each responsible for selecting one index of the triplet in increasing order.

result = 0
for i in range(len(nums)):
    for j in range(i + 1, len(nums)):
        for k in range(j + 1, len(nums)):
            value  = (nums[i] - nums[j]) * nums[k]
            result = max(result, value)
return result
  • The outer loop iterates i from the first element to the third-last element.
  • The middle loop selects j strictly after i.
  • The innermost loop picks k strictly after j.

For each combination, the expression (nums[i] - nums[j]) * nums[k] is evaluated and compared with the current result using the built-in max function. The variable result is initialized to 0, ensuring that the method always returns a non-negative integer.

Edge Cases Handled

When the input list contains fewer than three elements, the three nested loops never satisfy their range conditions. Consequently, the body of the loops is never executed, and the method returns the initial value 0. This behavior gracefully handles empty lists, single-element lists, and two-element lists without raising errors.

If the list includes negative numbers, the computed value may be negative. Because result starts at 0 and the comparison uses max, any negative result is ignored, and the method still returns the greatest non-negative value found (or 0 if none exist). This implicit handling of negative intermediate results ensures that the function never returns a negative answer.

Performance Optimizations Observed

Although the algorithm employs a brute-force triple-nested enumeration, a few subtle choices contribute to efficient execution:

  • The use of range(len(nums)) avoids repeated length calculations inside the loop bodies; the length is evaluated once per loop header.
  • The built-in max function performs the comparison in C code, which is faster than an equivalent Python conditional statement.
  • Direct indexing (nums[i], nums[j], nums[k]) accesses list elements in constant time without additional function calls.

These aspects keep the inner loop body lightweight, allowing the exhaustive search to run as quickly as possible given its combinatorial nature.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks lined up on the floor. Each block has a special number written on it. This program wants to play a game to find the biggest number it can create by picking three blocks from the line.

The program starts by looking at the first three blocks in the row. It picks one block, then a second one that comes after it, and a third one that comes after the second. It takes the number on the first block and subtracts the number on the second block. Then, it takes that answer and multiplies it by the number on the third block.

Because there are so many blocks, the program is very patient. It slides along the line to try every single combination of three blocks possible. Every time it finishes a math problem with a set of three blocks, it checks the result against the biggest result it has found so far. If the new result is bigger, it keeps that one instead. By the time it finishes looking at every single combination possible, it holds onto the largest number it managed to build.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.56 | σ = 1.17

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java Python C++ TS
WalkCCC Java Python C++
leetcode.ca Java Python C++ Go Rust TS
Progiez Java Python C++
github charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
varunu28 Java
23 links | 11 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 solutions   December 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality