bluecode-价格优惠计算问题

28 阅读2分钟

问题描述

小F在“双十一”期间购买了NN件商品。每件商品有一个价格p[i]p[i],小F可以获得的优惠取决于该商品之前的一件商品。如果某一件商品的价格p[i]p[i]大于等于前面的某个商品p[j]p[j],则小F可以享受该商品p[j]p[j]的价格作为优惠,前提是p[j]p[j]是离p[i]p[i]最近的且满足条件的商品。

例如,给定价格数组p = [9, 4, 5, 2, 4],其中p[3] = 2之前没有商品的价格小于等于p[3],因此没有优惠;而p[2] = 5可以享受最近的商品p[1] = 4的价格作为优惠。因此,任务是计算小F能获得的总优惠。


测试样例

样例1:

输入:N = 5 ,p = [9, 4, 5, 2, 4]
输出:6

样例2:

输入:N = 4 ,p = [1, 2, 3, 5]
输出:6

样例3:

输入:N = 4 ,p = [4, 3, 2, 1]
输出:0

#include <iostream>
#include <stack>
#include <vector>


using namespace std;

int solution(int N, std::vector<int> &prices) {
  int total_discount = 0;
  stack<int> s; // 存储商品索引的单调递增栈

  for (int i = 0; i < N; ++i) {
    while (!s.empty() && prices[s.top()] > prices[i]) {
      s.pop();
    }

    if (!s.empty()) {
      total_discount += prices[s.top()];
    }

    s.push(i);
  }

  return total_discount;
}

int main() {
  std::vector<int> p1 = {9, 4, 5, 2, 4};
  std::cout << (solution(5, p1) == 6) << std::endl;

  std::vector<int> p2 = {1, 2, 3, 5};
  std::cout << (solution(4, p2) == 6) << std::endl;

  std::vector<int> p3 = {4, 3, 2, 1};
  std::cout << (solution(4, p3) == 0) << std::endl;

  return 0;
}
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int solution(int N, std::vector<int>& prices) {
    int total_discount = 0;
    for (int i = 0; i < N; ++i) {
        int discount = 0;
        for (int j = i - 1; j >= 0; --j) {
            if (prices[i] >= prices[j]) {
                discount = prices[j];
                break;
            }
        }
        total_discount += discount;
    }
    return total_discount;
}

int main() {
    std::vector<int> p1 = {9, 4, 5, 2, 4};
    std::cout << (solution(5, p1) == 6) << std::endl;

    std::vector<int> p2 = {1, 2, 3, 5};
    std::cout << (solution(4, p2) == 6) << std::endl;

    std::vector<int> p3 = {4, 3, 2, 1};
    std::cout << (solution(4, p3) == 0) << std::endl;

    return 0;
}