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: 3
💡 Note: Choose subsequence [1,3] where first=1, last=3, product = 1×3 = 3. 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
Maximum Product of First and Last Elements INPUT Array nums: 1 i=0 -4 i=1 3 i=2 5 i=3 2 i=4 m = 3 (subseq size) Valid Subsequences: [1, -4, 3] [1, 3, 5] [1, 5, 2] [-4, 3, 5] [3, 5, 2] [1, -4, 5] Product = first * last of each subsequence ALGORITHM STEPS 1 Fix First Element Iterate through each possible starting index 2 Find Valid Last Elements Last must be at index >= first + (m-1) 3 Track Max/Min Values Keep max and min for negative number products 4 Compute Max Product For each first, multiply with best last element Product Calculations: 1*3=3, 1*5=5, 1*2=2 -4*5=-20, -4*2=-8 3*2=6 Max = 6? No, check [1,3,5]-->5 FINAL RESULT Best Subsequence Found: 1 first 3 5 last Product Calculation: 1 x 5 = 5 OUTPUT 5 [OK] Maximum product found Subsequence: [1, 3, 5] Key Insight: The two-pass approach optimizes by precomputing suffix max/min values. For each starting position i, the last element can be any value at index >= i + (m-1). Track both max and min suffix values because multiplying two negative numbers can yield a larger positive product. Time: O(n), Space: O(n). TutorialsPoint - Maximum Product of First and Last Elements of a Subsequence | Optimized Two-Pass Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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