购物消费打折

实现代码:

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);
    }
相关推荐
xiaoxue..14 分钟前
合并两个升序链表 与 合并k个升序链表
java·javascript·数据结构·链表·面试
忧郁的Mr.Li32 分钟前
SpringBoot中实现多数据源配置
java·spring boot·后端
啊森要自信33 分钟前
CANN ops-cv:AI 硬件端视觉算法推理训练的算子性能调优与实战应用详解
人工智能·算法·cann
yq1982043011561 小时前
静思书屋:基于Java Web技术栈构建高性能图书信息平台实践
java·开发语言·前端
一个public的class1 小时前
你在浏览器输入一个网址,到底发生了什么?
java·开发语言·javascript
有位神秘人1 小时前
kotlin与Java中的单例模式总结
java·单例模式·kotlin
golang学习记1 小时前
IntelliJ IDEA 2025.3 重磅发布:K2 模式全面接管 Kotlin —— 告别 K1,性能飙升 40%!
java·kotlin·intellij-idea
爬山算法1 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
java·压力测试·hibernate
仟濹1 小时前
算法打卡day2 (2026-02-07 周五) | 算法: DFS | 3_卡码网99_计数孤岛_DFS
算法·深度优先
驭渊的小故事1 小时前
简单模板笔记
数据结构·笔记·算法