Maximum Product of Two Elements in an Array
Real-world version: Best Pair Of Voucher PayoutsThe statement here is our own: the same inputs, outputs and technique.
A shop prints a run of vouchers. Voucher i shows the face value tokens[i], and handing it in converts to tokens[i] - 1 credits. Two vouchers may carry the same face value.
Choose two vouchers at different positions i and j. The payout for that choice is the product of their credit amounts. Return the largest payout any such choice gives.
Examples
Example 1
- Input
- tokens = [9, 4, 7, 1, 10]
- Output
- 72
Taking the vouchers showing 10 and 9 gives credits of 9 and 8, and their product is 72.
Example 2
- Input
- tokens = [6, 6, 2]
- Output
- 25
The two vouchers showing 6 sit at different positions, so both may be used. Each converts to 5 credits, and 5 times 5 is 25.
Example 3
- Input
- tokens = [1, 1000]
- Output
- 0
Only one pair exists. The voucher showing 1 converts to 0 credits, so the payout is 0 times 999, which is 0.
Constraints
- 2 <= tokens.length <= 500
- 1 <= tokens[i] <= 10^3
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def max_product(tokens: list[int]) -> int:public int maxProduct(int[] tokens)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 9 test cases: 9 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Minimum Number GameReal-world version: Shelving Boxes in TurnsEasy
- High FiveReal-world version: Top Five Average per ApprenticeEasy
- Make Array Zero by Subtracting Equal AmountsReal-world version: Rounds Needed to Clear Every ReadingEasy
- Find Subsequence of Length K With the Largest SumReal-world version: Keeping the k Best Readings in PlaceEasy