通过替换元素来最小化数组总和,从而保持相邻元素之间的关系
给定一个大小为 N 的数组arr[] ,任务是在用正整数替换数组元素后最小化数组和,以保持相邻元素(数组的模式)之间的关系。
注意:如果 arr[i] = arr[i+1] 那么在新数组中它们可以相同,或者一个可以小于另一个。
例子:
Input: arr[] = [ 2, 1, 3]
Output: 5
Explanation: The redesigned array will be [2, 1, 2]. Sum = 5
Here arr[0] > arr[1] and arr[1] < arr[2] i.e. the relation among adjacent elements is unchanged.
This is the minimum sum possible after replacements
Input: arr[] = [ 4, 5, 5]
Output: 4
Explanation: We can redesign array as [1, 2, 1].
arr[0] < arr[1] and arr[1] >= arr[2] which satisfies the condition of the question.
So the minimum possible sum is 1+2+1 = 4
方法:这个问题可以根据以下观察来解决:
- All the elements which are equal to or less than both its previous and next elements can be replaced by the smallest value i.e 1.
- The smallest possible value for an element is dependent on the number of contiguous smaller elements in its left (say X) and in its right (say Y). So the smallest possible value is maximum between X+1 and Y+1.
按照下面提到的步骤解决问题
- 声明一个数组(比如ans[] )来存储替换后新形成的数组,并将所有元素初始化为 1。
- 从 i = 1 遍历arr[]到 N-1 。
- 如果arr[i] > arr[i-1],则将ans[i]设置为ans[i-1] +1 ,因为这会将数组元素的值设置为arr[左侧的连续较小元素的数量我] 。
- 现在遍历数组arr[]从i = N-2 到 0 。
- 如果arr[i] > arr[i + 1] ,则将ans[i]设置为max(ans[i+1] +1, ans[i])因为它将元素设置为具有最大数量的值任何一侧的连续元素。
- 返回总和 新形成的数组即ans[] 。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
int marks(vector& A)
{
// Making vector v and assigning 1
// to all elements
vector ans(A.size(), 1);
// Traversing to check from left
// If element is of higher value we will
// add 1 to previous element
for (int i = 1; i < A.size(); i++)
if (A[i] > A[i - 1])
ans[i] = ans[i - 1] + 1;
// Traversing from right we will check
// whether it has value sastisfying both
// side If element is of higher value we
// will add 1 to previous element
for (int i = A.size() - 2; i >= 0; i--)
if (A[i] > A[i + 1])
ans[i] = max(ans[i],
ans[i + 1] + 1);
// Accumulating the array
// and returning the sum
int sum = 0;
for (int s : ans)
sum += s;
return sum;
}
// Driver code
int main()
{
// Initilazing a vector
vector arr = { 4, 5, 5 };
// Function call
cout << marks(arr) << endl;
return 0;
}
4
时间复杂度: O(N)
辅助空间: O(N)