购物消费打折

实现代码:

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);
    }
相关推荐
6***8305几秒前
微服务搭建----springboot接入Nacos2.x
java
likuolei1 小时前
XML 元素 vs. 属性
xml·java·开发语言
自不量力的A同学1 小时前
Spring Boot 4.0.0 正式发布
java·spring boot·后端
d***29241 小时前
【spring】Spring事件监听器ApplicationListener的使用与源码分析
java·后端·spring
5***b971 小时前
解决报错net.sf.jsqlparser.statement.select.SelectBody
java
q***95221 小时前
Tomcat下载,安装,配置终极版(2024)
java·tomcat
2***d8852 小时前
详解tomcat中的jmx监控
java·tomcat
无敌最俊朗@2 小时前
Qt事件循环队列剖析!!!
java
v***5652 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
做怪小疯子2 小时前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵