类似于这种题目 数据可能有所出入
答案代码如下
#include <iostream>
#include <vector>
#include <algorithm>
int maxProfit(std::vector<int>& price, int n) {
std::vector<int> dp(n + 1, 0);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] = std::max(dp[i], price[j] + dp[i - j]);
}
}
return dp[n];
}
int main() {
std::vector<int> price = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; // 长度为 i 的钢条的售价
int n;
std::cout << "Enter the length of the steel rod: ";
std::cin >> n;
int profit = maxProfit(price, n);
std::cout << "Maximum profit: " << profit << std::endl;
return 0;
}
那么假如dp[2]>price[2] 那么i=4的钢管的最大值就有可能是两个dp[2] 但是在 dp[i] = std::max(dp[i], price[j] + dp[i - j]);中 并不会出现两个dp[2]相加的情况 那么这个代码是如何保证的得到的dp[4]值一定不小于两个dp[2]之和的呢