Introduction
LeetCode 3689, “Maximum Total Subarray Value I”, is an interesting medium-level array problem that focuses on maximizing the total value of selected subarrays. The challenge introduces an important observation-based greedy approach that simplifies the problem significantly.
In this article, we will break down the problem statement, understand the intuition behind the solution, analyze the Java code step-by-step, and discuss the time and space complexity.
Problem Statement
Try this problem here :- Maximum Total Subarray Value I
You are given:
- An integer array
nums - An integer
k
You must choose exactly k non-empty subarrays from the array.
The value of a subarray is defined as:
Value = Maximum Element − Minimum Element
The goal is to maximize the total value of all chosen subarrays.
Example
Example 1
Input:
Output:
Explanation:
- Subarray
[1,3]→3 - 1 = 2 - Subarray
[1,3,2]→3 - 1 = 2
Total = 2 + 2 = 4
Example 2
Input:
Output:
Explanation:
The maximum possible subarray value is:
Choose this optimal subarray 3 times:
Key Observation
The problem allows:
- Overlapping subarrays
- Reusing the same exact subarray multiple times
This changes everything.
To maximize the total value:
- Find the maximum possible subarray value.
- Reuse that same subarray exactly
ktimes.
Now the question becomes:
What is the maximum possible value of any subarray?
Since a subarray’s value is:
The largest possible value is simply:
So the final answer becomes:
Java Solution
Step-by-Step Dry Run
Input
Step 1: Find Minimum and Maximum
Traverse the array:
| Element | Current Min | Current Max |
| 4 | 4 | 4 |
| 2 | 2 | 4 |
| 5 | 2 | 5 |
| 1 | 1 | 5 |
Final:
Step 2: Calculate Maximum Subarray Value
Step 3: Multiply by k
Final Answer:
Why This Greedy Approach Works
The problem explicitly allows selecting:
- The same subarray multiple times
- Overlapping subarrays
So once we identify the subarray with the highest possible value, there is no reason to choose anything else.
The optimal strategy is:
This reduces the entire problem to finding:
Time Complexity
Time Complexity
We traverse the array only once.
Space Complexity
Only a few variables are used.
Interview Insights
This problem tests:
- Observation skills
- Greedy thinking
- Ability to simplify constraints
- Understanding of problem flexibility
Many developers initially overcomplicate the problem using sliding window or dynamic programming approaches. However, the key insight is realizing that repeated subarrays are allowed.
Final Thoughts
LeetCode 3689 is a great example of how carefully reading constraints can dramatically simplify a problem.
Instead of generating all subarrays, the optimal solution comes from a simple mathematical observation:
This leads to an elegant and highly efficient O(n) solution.
If you are preparing for coding interviews, this problem is an excellent exercise in greedy optimization and pattern recognition.





