购物消费打折

实现代码:

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 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌3 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
华仔啊5 小时前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang5 小时前
用六边形架构与整洁架构对比是伪命题?
java·架构
AI软著研究员5 小时前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish5 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Ray Liang6 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
颜酱6 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
Java水解6 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端
SimonKing10 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员