You're given an array of integers nums with n elements, and your task is to divide it into exactly 3 disjoint contiguous subarrays.
The cost of any subarray is defined as the value of its first element. For example:
- The cost of
[1, 2, 3]is1 - The cost of
[3, 4, 1]is3
Your goal is to find the minimum possible sum of the costs of these three subarrays. Since we need exactly 3 subarrays, we need to place 2 dividers in the array, creating 3 contiguous segments.
Key insight: The first subarray always starts at index 0, so its cost is always nums[0]. We only need to choose where the second and third subarrays begin!
Input & Output
Visualization
Time & Space Complexity
In worst case, we still need to check all valid combinations, but with optimizations
Only using constant extra space for variables
Constraints
- 3 โค nums.length โค 50
- 1 โค nums[i] โค 50
- The array must be divided into exactly 3 non-empty contiguous subarrays