购物消费打折

实现代码:

java 复制代码
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int k = sc.nextInt();
        
        int[] prices = new int[n];
        for (int i = 0; i < n; i++) {
            prices[i] = sc.nextInt();
        }
        
        String discountStr = sc.next();
        
        List<Integer> discountItems = new ArrayList<>();
        List<Integer> noDiscountItems = new ArrayList<>();
        
        for (int i = 0; i < n; i++) {
            if (discountStr.charAt(i) == '1') {
                discountItems.add(prices[i]);
            } else {
                noDiscountItems.add(prices[i]);
            }
        }
        
        // 排序
        Collections.sort(discountItems);
        Collections.sort(noDiscountItems);
        
        int i = 0, j = 0;
        int count = 0;
        double balance = k;
        
        while (i < discountItems.size() && j < noDiscountItems.size()) {
            double discPrice = discountItems.get(i) * 0.95;
            int noDiscPrice = noDiscountItems.get(j);
            
            if (discPrice <= noDiscPrice) {
                if (balance >= discPrice) {
                    balance -= discPrice;
                    count++;
                    i++;
                } else {
                    break;
                }
            } else {
                if (balance >= noDiscPrice) {
                    balance -= noDiscPrice;
                    count++;
                    j++;
                } else {
                    break;
                }
            }
        }
        
        // 处理剩余优惠物品
        while (i < discountItems.size()) {
            double discPrice = discountItems.get(i) * 0.95;
            if (balance >= discPrice) {
                balance -= discPrice;
                count++;
                i++;
            } else {
                break;
            }
        }
        
        // 处理剩余非优惠物品
        while (j < noDiscountItems.size()) {
            int noDiscPrice = noDiscountItems.get(j);
            if (balance >= noDiscPrice) {
                balance -= noDiscPrice;
                count++;
                j++;
            } else {
                break;
            }
        }
        
        System.out.println(count);
    }
相关推荐
学编程就要猛1 分钟前
Spring AI Alibaba(上)
java·人工智能·spring·springaialibaba
stolentime8 分钟前
AT_arc182_a [ARC182A] Chmax Rush!题解
数据结构·c++·算法·动态规划
longlongzihan9 分钟前
LeetCode 189. 轮转数组:从直观模拟到最优原地算法
c++·算法·leetcode
爱喝热水的呀哈喽14 分钟前
cpp二分库函数 lambda捕获
算法
imDwAaY14 分钟前
Spring Boot的核心配置文件一览及其加载顺序
java·spring boot·后端
zhangx1234_17 分钟前
javaEE 多线程1
java·linux·服务器
鬼手点金21 分钟前
opencode-crawl4ai使用建议
java·开发语言·人工智能·python·机器学习
longlongzihan24 分钟前
LeetCode 76. 最小覆盖子串:滑动窗口算法详解
算法·leetcode·滑动窗口
专业程序开发源36 分钟前
springboot校园志愿者管理系统28562-计算机课程设计、毕业设计
java·spring boot·后端·python·django·php·课程设计
thefool11226640 分钟前
多线程 2
java