Divide an Array Into Subarrays With Minimum Cost I - Problem

You are given an array of integers nums of length n.

The cost of an array is the value of its first element. For example, the cost of [1,2,3] is 1 while the cost of [3,4,1] is 3.

You need to divide nums into 3 disjoint contiguous subarrays.

Return the minimum possible sum of the cost of these subarrays.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 6
💡 Note: Divide into [1], [2], [3,4]. Costs are 1, 2, 3. Total = 1+2+3 = 6. This is minimum among all possible divisions.
Example 2 — Different Values
$ Input: nums = [6,2,7,4,1]
Output: 9
💡 Note: Divide into [6], [2,7,4], [1]. Costs are 6, 2, 1. Total = 6+2+1 = 9. This is minimum among all possible divisions.
Example 3 — Minimum Size
$ Input: nums = [20,6,2]
Output: 28
💡 Note: Only one way to divide into 3 subarrays: [20], [6], [2]. Costs are 20, 6, 2. Total = 20+6+2 = 28.

Constraints

  • 3 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 50

Visualization

Tap to expand
Divide Array Into Subarrays - Minimum Cost INPUT Array nums (length n=4) 1 idx 0 2 idx 1 3 idx 2 4 idx 3 Cost Definition Cost = First element of subarray Example: cost([1,2,3]) = 1 Goal Split into 3 contiguous parts nums = [1, 2, 3, 4] ALGORITHM STEPS 1 First subarray cost Always nums[0] = 1 2 Find 2 smallest From nums[1] to nums[n-1] 3 Single pass scan Track min1 and min2 4 Calculate result nums[0] + min1 + min2 Scanning [2, 3, 4] i=1: val=2 min1=2, min2=INF i=2: val=3 min1=2, min2=3 i=3: val=4 min1=2, min2=3 Result: 1 + 2 + 3 = 6 FINAL RESULT Optimal Split: [1] cost=1 [2] cost=2 [3,4] cost=3 Sum of Costs 1 + 2 + 3 = 6 OUTPUT 6 Minimum possible sum [OK] Verified correct! Key Insight: The first subarray MUST start at index 0, so its cost is always nums[0]. For the other two subarrays, we want to minimize their starting elements. We just need the two smallest elements from nums[1..n-1]. Time: O(n), Space: O(1) TutorialsPoint - Divide an Array Into Subarrays With Minimum Cost I | Single Pass with Early Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
15.8K Views
Medium Frequency
~15 min Avg. Time
420 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