#3117
Minimum Sum of Values by Dividing Array
HardArrayBinary SearchDynamic ProgrammingBit ManipulationSegment TreeQueueDynamic ProgrammingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n * m) |
💡
Intuition
Time O(n * m)Space O(n * m)
The optimal solution uses dynamic programming to efficiently calculate the minimum sum by storing results of subproblems. This avoids redundant calculations and allows us to build up the solution incrementally.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i][j] represents the minimum sum of the last elements of the first j subarrays formed from the first i elements of nums.
- 2Step 2: Iterate through nums and for each element, check possible subarrays that can end at that element and match the corresponding andValue.
- 3Step 3: Update the DP array based on the valid partitions found, ensuring to keep track of the minimum sum.
solution.py20 lines
1# Full working Python code
2import sys
3
4
5def min_sum_partition(nums, andValues):
6 n = len(nums)
7 m = len(andValues)
8 dp = [[sys.maxsize] * (m + 1) for _ in range(n + 1)]
9 dp[0][0] = 0
10
11 for j in range(1, m + 1):
12 for i in range(1, n + 1):
13 and_value = nums[i - 1]
14 for z in range(i, 0, -1):
15 and_value &= nums[z - 1]
16 if and_value == andValues[j - 1]:
17 dp[i][j] = min(dp[i][j], dp[z - 1][j - 1] + nums[i - 1])
18 if and_value == 0:
19 break
20 return dp[n][m] if dp[n][m] != sys.maxsize else -1ℹ
Complexity note: The time complexity is O(n * m) because we iterate through each element of nums and for each element, we check possible subarrays for each value in andValues.
- 1Understanding bitwise operations is crucial for solving this problem.
- 2Dynamic programming can significantly reduce the complexity of problems involving partitions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.