LeetCode:1475. Final Prices With a Special Discount in a Shop商品折扣后的最终价格(C语言)

一时失言乱红尘 2022-12-29 14:12 135阅读 0赞

题目描述:
给你一个数组 prices ,其中 prices[i] 是商店里第 i 件商品的价格。

商店里正在进行促销活动,如果你要买第 i 件商品,那么你可以得到与 prices[j] 相等的折扣,其中 j 是满足 j > i 且 prices[j] <= prices[i] 的 最小下标 ,如果没有满足条件的 j ,你将没有任何折扣。

请你返回一个数组,数组中第 i 个元素是折扣后你购买商品 i 最终需要支付的价格。

示例 1:

输入:prices = [8,4,6,2,3]
输出:[4,2,4,2,3]
解释:
商品 0 的价格为 price[0]=8 ,你将得到 prices[1]=4 的折扣,所以最终价格为 8 - 4 = 4 。
商品 1 的价格为 price[1]=4 ,你将得到 prices[3]=2 的折扣,所以最终价格为 4 - 2 = 2 。
商品 2 的价格为 price[2]=6 ,你将得到 prices[3]=2 的折扣,所以最终价格为 6 - 2 = 4 。
商品 3 和 4 都没有折扣。

示例 2:

输入:prices = [1,2,3,4,5]
输出:[1,2,3,4,5]
解释:在这个例子中,所有商品都没有折扣。

示例 3:

输入:prices = [10,1,1,6]
输出:[9,0,1,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/final-prices-with-a-special-discount-in-a-shop
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:

  1. /** * Note: The returned array must be malloced, assume caller calls free(). */
  2. int* finalPrices(int* prices, int pricesSize, int* returnSize){
  3. *returnSize = pricesSize;
  4. int i = 0;
  5. int j = 0;
  6. int temp = 0;
  7. int *res = (int*)malloc(sizeof(int) * pricesSize);
  8. for(i = 0; i < pricesSize;i++){
  9. res[i] = prices[i];
  10. for(j = i + 1;j <pricesSize;j++){
  11. temp = 0;
  12. if(prices[j] <= prices[i]){
  13. temp = prices[i] - prices[j];
  14. res[i] = temp;
  15. break;
  16. }
  17. }
  18. }
  19. return res;
  20. }

运行结果:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,135人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C语言a++和++a

    \++有两种形式:<1>一种为前缀++:++a;<2>一种则为后缀++:a++ 现在我们来讨论下前缀++: 前缀形式的++放在操作数之前,则操作数的值先被增加即表达式的值就