在 C++ 中查找数组的最小调整成本
概念
对于给定的正整数数组,我们替换数组中的每个元素,使得数组中相邻元素之间的差小于或等于给定的目标值。现在,我们的任务是最小化调整成本,即新旧值之间差异的总和。因此,我们基本上需要最小化 Σ|A[i] – Anew[i]|,其中 0 ≤ i ≤ n-1,n 表示 A[] 的大小,Anew[] 表示相邻差小于或等于目标值的数组。假设数组的所有元素都小于常数 M = 100。
输入
arr = [56, 78, 53, 62, 40, 7, 26, 61, 50, 48], target = 20
输出
Minimum adjustment cost is 35
方法
为了最小化调整成本 Σ|A[i] – Anew[i]|,对于数组中的所有索引 i,我们记住 |A[i] – Anew[i]| 应尽可能接近零。需要注意的是,
|A[i] – Anew[i+1] ]| ≤ 目标值。
这里,这个问题可以通过动态规划 (DP) 来解决。
假设 dp1[i][j] 表示将 A[i] 更改为 j 的最小调整成本,则 DP 关系定义为:
dp1[i][j] = min{dp1[i - 1][k]} + |j - A[i]|
对于所有满足 |k - j| ≤ 目标值的 k。
在这种情况下,0 ≤ i ≤ n 且 0 ≤ j ≤ M,其中 n 是数组中元素的数量,M = 100。因此,所有 k 值都以这种方式考虑,使得 max(j – 目标值, 0) ≤ k ≤ min(M, j + 目标值)。最后,数组的最小调整成本将是 min{dp1[n – 1][j]},对于所有 0 ≤ j ≤ M。
示例
// C++ program to find minimum adjustment cost of an array
#include <bits/stdc++.h>
using namespace std;
#define M1 100
//Shows function to find minimum adjustment cost of an array
int minAdjustmentCost(int A1[], int n1, int target1){
// dp1[i][j] stores minimal adjustment cost on changing
// A1[i] to j
int dp1[n1][M1 + 1];
// Tackle first element of array separately
for (int j = 0; j <= M1; j++)
dp1[0][j] = abs(j - A1[0]);
// Perform for rest elements of the array
for (int i = 1; i < n1; i++){
// Now replace A1[i] to j and calculate minimal adjustment
// cost dp1[i][j]
for (int j = 0; j <= M1; j++){
// We initialize minimal adjustment cost to INT_MAX
dp1[i][j] = INT_MAX;
// We consider all k such that k >= max(j - target1, 0)
and
// k <= min(M1, j + target1) and take minimum
for (int k = max(j-target1,0); k <= min(M1,j+target1);
k++)
dp1[i][j] = min(dp1[i][j], dp1[i - 1][k] + abs(A1[i] -j));
}
}
//Now return minimum value from last row of dp table
int res1 = INT_MAX;
for (int j = 0; j <= M1; j++)
res1 = min(res1, dp1[n1 - 1][j]);
return res1;
}
// Driver Program to test above functions
int main(){
int arr1[] = {56, 78, 53, 62, 40, 7, 26, 61, 50, 48};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int target1 = 20;
cout << "Minimum adjustment cost is "
<< minAdjustmentCost(arr1, n1, target1) << endl;
return 0;
}输出
Minimum adjustment cost is 35
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP