描述
金属棒工厂的厂长拥有 n 根多余的金属棒。 当地的一个承包商提出,只要所有的棒材具有相同的长度(用 saleLength 表示棒材的长度),就将金属棒工厂的剩余棒材全部购买。 厂长可以通过将每根棒材切割零次或多次来增加可销售的棒材数量,但是每次切割都会产生一定的成本(用 costPerCut 表示每次切割的成本)。 等所有的切割完成以后,多余的棒材将被丢弃,没有利润。
金属棒工厂的厂长获得的销售总利润计算公式如下:
totalProfit = totalUniformRods * saleLength * salePrice - totalCuts * costPerCut
其中 totalUniformRods 是可销售的金属棒数量, salePrice 是承包商同意支付的每单位长度价格, totalCuts是需要切割棒材的次数。
样例 1
输入:
1
10
[30,59,110]
输出:
1913
https://www.lintcode.com/problem/cutting-metal-surplus/description
class Solution {
public:
/**
* @param costPerCut: integer cost to make a cut
* @param salePrice: integer per unit length sales price
* @param lengths: an array of integer rod lengths
* @return: The function must return an integer that denotes the maximum possible profit.
*/
int maxProfit(int costPerCut, int salePrice, vector<int> &lengths) {
// write your code here
int maxprofit = 0, profit = 0;
for(int L = 1; L <= 10000; ++L)
{
profit = 0;
for(auto l : lengths)
{
int n = l/L;
int cut = 0;
if(l%L == 0)
cut = n-1;
else
cut = n;
profit += n*salePrice*L - cut*costPerCut;
}
maxprofit = max(maxprofit, profit);
}
return maxprofit;
}
};
101ms C++