Maximum Product of First and Last Elements of a Subsequence - Problem
You are given an integer array nums and an integer m.
Return the maximum product of the first and last elements of any subsequence of nums of size m.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,-4,3,5,2], m = 3
›
Output:
5
💡 Note:
Choose subsequence [1,3,5] where first=1, last=5, product = 1×5 = 5. Or choose [1,5,2] where first=1, last=2, product = 1×2 = 2. The maximum is 5.
Example 2 — Negative Numbers
$
Input:
nums = [-2,1,3,-1], m = 2
›
Output:
2
💡 Note:
Choose subsequence [-2,-1] where first=-2, last=-1, product = (-2)×(-1) = 2. This gives the maximum product among all possible subsequences of size 2.
Example 3 — Same Elements
$
Input:
nums = [4,4,4,4], m = 3
›
Output:
16
💡 Note:
Any subsequence of size 3 will have first=4 and last=4, so the product is 4×4 = 16.
Constraints
- 2 ≤ nums.length ≤ 104
- 2 ≤ m ≤ nums.length
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,-4,3,5,2] with m=3
2
Process
Find all valid subsequences of size 3
3
Output
Maximum product of first×last = 5
Key Takeaway
🎯 Key Insight: Only the first and last elements matter in the product calculation, so we can efficiently check all valid first-last pairs instead of generating complete subsequences.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code