Maximum Product of First and Last Elements of a Subsequence - Problem

You are given an integer array nums and an integer m. Your task is to find a subsequence of exactly m elements that maximizes the product of its first and last elements.

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.

Goal: Return the maximum possible product of the first and last elements among all subsequences of size m.

Example: For nums = [1, 5, 3, 2, 4] and m = 3, one optimal subsequence is [5, 3, 4] where the product of first and last elements is 5 ร— 4 = 20.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 5, 3, 2, 4], m = 3
โ€บ Output: 20
๐Ÿ’ก Note: We can choose subsequence [5, 3, 4] (indices 1, 2, 4). The product of first and last elements is 5 ร— 4 = 20, which is the maximum possible.
example_2.py โ€” Single Element
$ Input: nums = [2, 4, 6], m = 1
โ€บ Output: 36
๐Ÿ’ก Note: When m = 1, the subsequence contains only one element, so we multiply it by itself. The maximum element is 6, giving us 6 ร— 6 = 36.
example_3.py โ€” Negative Numbers
$ Input: nums = [-2, 1, -3, 4, -1], m = 2
โ€บ Output: 6
๐Ÿ’ก Note: The optimal subsequence is [-2, -3] with product (-2) ร— (-3) = 6. Two negative numbers give a positive product, which is better than any combination involving positive numbers here.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค m โ‰ค nums.length
  • -104 โ‰ค nums[i] โ‰ค 104
  • Subsequence must maintain relative order of elements

Visualization

Tap to expand
โ™Ÿ๏ธ Chess Tournament Selection StrategyOriginal Player Lineup15324Sorted by Rating (with original positions)5pos:14pos:43pos:22pos:31pos:0Optimal Team Selection (m=3)Choose First: Player 5 (pos 1), Last: Player 4 (pos 4)534Prize: 5 ร— 4 = 20 ๐Ÿ†๐Ÿ’ก Key InsightBetween positions 1 and 4, we have positions 2,3 (2 spots available)We need exactly 1 player between first and last (m=3 total)Since 2 โ‰ฅ 1, this selection is VALID! โœ“
Understanding the Visualization
1
Rank All Players
Sort players by rating while remembering their original positions
2
Try Best Combinations
Consider pairs of high-rated players as potential first and last
3
Check Team Size
Verify we can fill the team with enough players between chosen first and last
4
Maximize Prize
Pick the combination that gives the highest product
Key Takeaway
๐ŸŽฏ Key Insight: Sort by value to prioritize high products, then verify feasibility by checking if enough positions exist between chosen first and last elements.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
31.7K Views
Medium Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen