LeetCode 3117: Minimum Sum of Values by Dividing Array Solution
Master LeetCode problem 3117 (Minimum Sum of Values by Dividing Array), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3117. Minimum Sum of Values by Dividing Array
Problem Explanation
Explanation
To solve this problem, we can iterate through the andValues array and find the subarrays in nums that satisfy the condition of having the same bitwise AND value as specified in andValues. We can achieve this by keeping track of the prefix AND values of nums and using dynamic programming to find the valid subarrays.
- Initialize an array
prefixAndto store the prefix AND values ofnums. - Iterate over the
andValuesarray and find the subarrays that satisfy the condition. - Use dynamic programming to find the minimum sum of values for the subarrays.
- Return the minimum sum or -1 if no valid subarrays are found.
Time complexity: O(n * m) where n is the length of nums and m is the length of andValues.
Space complexity: O(n) for storing the prefix AND values of nums.
Solution Code
class Solution {
public int minimumSum(int[] nums, int[] andValues) {
int n = nums.length;
int m = andValues.length;
int[] prefixAnd = new int[n];
prefixAnd[0] = nums[0];
for (int i = 1; i < n; i++) {
prefixAnd[i] = prefixAnd[i - 1] & nums[i];
}
int[][] dp = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
for (int i = 0; i < n; i++) {
dp[i][0] = (i == 0) ? nums[i] : Math.min(dp[i - 1][0], nums[i]);
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
for (int k = 0; k < i; k++) {
if ((prefixAnd[i] & andValues[j]) == andValues[j]) {
dp[i][j] = Math.min(dp[i][j], dp[k][j - 1] + (i == k + 1 ? nums[i] : prefixAnd[i] - prefixAnd[k]));
}
}
}
}
int minSum = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
minSum = Math.min(minSum, dp[i][m - 1]);
}
return minSum == Integer.MAX_VALUE ? -1 : minSum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3117 (Minimum Sum of Values by Dividing Array)?
This page provides optimized solutions for LeetCode problem 3117 (Minimum Sum of Values by Dividing Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3117 (Minimum Sum of Values by Dividing Array)?
The time complexity for LeetCode 3117 (Minimum Sum of Values by Dividing Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3117 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3117 in Java, C++, or Python.