使用相邻元素之间的给定关系最小化 Array 的总和
给定一个长度为N的二进制字符串S ,由 0 和 1 组成,任务是找到通过以下条件创建的长度为N+1的非负整数数组的最小和:
- 如果给定二进制字符串中的第 i 个数字是0 ,那么数组中的第 (i + 1) 个数字必须小于第 i 个数字。
- 如果给定二进制字符串中的第 i 个数字是1 ,则数组中的第 (i + 1) 个数字必须大于第 i 个数字。
例子:
Input: N = 3, S = “100”
Output: 3
Explanation: We can create the array [0, 2, 1, 0].
So total sum will be 0 + 2 + 1 + 0 = 3.
Hence, resultant array follows the conditions, and ‘3’ is the minimum value we can achieve.
Input: N = 3, S = “101”
Output: 2
Explanation: We can create the array [0, 1, 0, 1].
So total sum will be 0 + 1 + 0 + 1 = 2.
Hence, resultant array follows the conditions, and ‘2’ is the minimum value we can achieve.
方法:这个问题可以通过使用来解决 基于以下观察的贪婪方法:
- Consider we have K consecutive 1, in this case, last value will be at least K, as array would look something like this [0, 1, 2, …, K – 1, K], this would give us a minimum sum.
- Same thing if we have K consecutive 0, in this case, array will look something like this [K, K – 1, …, 2, 1, 0], hence our first value will be at least K.
- Thus the ith element of the answer array will be the maximum among consecutive 1’s to its left and consecutive 0’s to its right.
If we take a value greater than the maximum value, we will increase our sum, and hence the sum will not be minimum. If we take any less value than the maximum value, then one of the values in the array will become less than 0, which is a violation of the condition.
请按照以下步骤解决此问题:
- 构造两个长度为N + 1的数组(例如arr1[] 和 arr2[] )并将所有值填充为“0”。
- 从i = 0 遍历到 N – 1 。
- 如果 S[i] 值为 1,则设置 arr1[i+1] = arr1[i]+1。
- 从i = N – 1 遍历到 0 。
- 如果 S[i] 值为 0,则设置 arr2[i] = arr2[i+1]+1。
- 从i = 0 到 N遍历两个数组:
- 将 arr1[i] 和 arr2[i] 的最大值添加到答案中。
- 返回答案。
以下是上述方法的实现:
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to calculate the sum
long long minimumSum(string& s, int n)
{
vector arr1(n + 1, 0), arr2(n + 1, 0);
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s[i] == '1') {
arr1[i + 1] = arr1[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr2[i] = arr2[i + 1] + 1;
}
}
long long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += max(arr1[i], arr2[i]);
}
return ans;
}
// Driver Code
int main()
{
int N = 3;
string S = "101";
// fzunction call
cout << minimumSum(S, N);
return 0;
}
2
时间复杂度:O(N)
辅助空间O(N)