在 LeetCode 商店中, 有 n 件在售的物品。每件物品都有对应的价格。然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。
给你一个整数数组 price 表示物品价格,其中 price[i] 是第 i 件物品的价格。另有一个整数数组 needs 表示购物清单,其中 needs[i] 是需要购买第 i 件物品的数量。
还有一个数组 special 表示大礼包,special[i] 的长度为 n + 1 ,其中 special[i][j] 表示第 i 个大礼包中内含第 j 件物品的数量,且 special[i][n] (也就是数组中的最后一个整数)为第 i 个大礼包的价格。
返回 确切 满足购物清单所需花费的最低价格,你可以充分利用大礼包的优惠活动。你不能购买超出购物清单指定数量的物品,即使那样会降低整体价格。任意大礼包可无限次购买。
每个商品只会出现在一种折扣中
needs = [2,17,3,5]
表明 买17个2和5个三
promotionsColSize[i] = 2
promotions[i] = [2,4]
discount[i] = 20
表示2号如果有4个的话,可以减少20元
promotionsColSize[i] = 4
promotions[i] = [2,4,3,2]
discount[i] = 10
表示2号如果有4个的话,3号有2个,可以减少10元
思路
- 每个商品只会出现在一种折扣中,那就每种商品直接按照折扣中的最大值来算,贪心
- 先计算总价,再进行减除
#include<stdio.h>
#define ID_MAX 1001
#define COUNT 2
int GetPrice(int* promotions, int promotionsColSize, int discount, int orderCount[ID_MAX], int *prices){
int sum;
int min = 0x7fffffff;
int i = 0;
for (i = 0; i < promotionsColSize; i++) {
sum += prices[promotions[i]] * orderCount[promotions[i]]; //总价
min = min < orderCount[promotions[i]] / promotions[i+1] ? min : orderCount[promotions[i]] / promotions[i+1];//每种折扣组合中的最小符合数量
orderCount[promotions[i]] = 0;//总价已经加上了直接赋值为0就行
i++;
}
return sum - min * discount;//减去折扣
}
int shoppingOffers(int* prices, int priceSize, int** promotions, int promotionsSize, int* promotionsColSize,
int *discounts, int discountsSize, int* order, int orderSize){
int res = 0;
int i = 0;
int orderCount[ID_MAX] = {0};
for (i = 0; i < orderSize; i++) {
orderCount[order[i]] = order[i + 1];
i++;
}
for (i = 0; i < promotionsSize; i++) {
if(promotionsColSize[i] == 2) {//只有一个折扣的
int id = promotions[i][0];
res += (prices[id] * orderCount[id] -orderCount[id] / promotions[i][i] *discounts[i]);
orderCount[id] = 0;
} else {//有一堆组合才折扣的
res += GetPrice(promotions[i], promotionsColSize[i], discounts[i], orderCount, prices);
}
}
for (i = 0; i < priceSize; i++) {//没有折扣的
res += prices[i] * orderCount[i];
}
return res;
}