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
Difficulty
and has an acceptance rate of about 58% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
AI Disclaimer
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.
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
ifrom the first element to the third-last element. - The middle loop selects
jstrictly afteri. - The innermost loop picks
kstrictly afterj.
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
maxfunction 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 2367: Number of Arithmetic Triplets
- problem 2908: Minimum Sum of Mountain Triplets I
Solved On The Same Day
- problem 1592: Rearrange Spaces Between Words
- problem 1688: Count of Matches in Tournament
- problem 2937: Make Three Strings Equal
- problem 2434: Using a Robot to Print the Lexicographically Smallest String
- problem 2516: Take K of Each Character From Left and Right
- problem 2610: Convert an Array Into a 2D Array With Conditions
- problem 2671: Frequency Tracker
- problem 2711: Difference of Number of Distinct Values on Diagonals
- problem 2766: Relocate Marbles
Extra
- 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