购物消费打折

实现代码:

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);
    }
相关推荐
智码看视界4 小时前
Day19 Spring Boot启动优化:启动时间从8秒降到2秒
java·spring boot·后端·启动优化
hongyucai4 小时前
详解rlinf强化学习四步曲
人工智能·python·算法·架构
变量未定义~4 小时前
ST表-龙骑士军团【算法赛】
数据结构·算法
北京阿法龙科技有限公司4 小时前
AR智能眼镜安防应用核心指标:识别距离筑牢防线
java·开发语言·ar
殘殤血4 小时前
Tomcat的事件监听机制:观察者模式 _
java·观察者模式·tomcat
汤姆yu4 小时前
面向具身智能的物理视频模拟器:蚂蚁灵波LingBot-Video开源模型全解析
java·大数据·人工智能·gpt·开源·大模型·音视频
小帽子_1235 小时前
储能 SOC/SOH 精准估算技术:储能工况下算法优化与误差修正方案
算法
SQL-First布道者5 小时前
Spring JDBC Ultra 十边型战士
java·spring boot·后端·mysql·spring·mybatis
hhlongg5 小时前
FFT分析
算法
殘殤血5 小时前
Tomcat的事件监听机制:观察者模式
java·观察者模式·tomcat