华为OD机试真题-最大利润【C++ Java Python】

本文通过一个华为OD机试真题介绍了如何使用贪心算法解决最大利润问题。题目中商人需要根据商品价格变化进行买卖以获取最大利润,每种商品有限的库存限制。解题思路是逐天比较价格,当价格上涨时买入,下降时卖出。文章提供了Java、Python和C++三种语言的解题代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


目录

题目内容

解题思路

Java代码

Python代码

C++代码

题目内容


商人经营一家店铺,有number 种商品,
由于仓库限制每件商品的最大持有数量是 item[index]
每种商品的价格是 price[item_index][day]
通过对商品的买进和卖出获取利润
请给出商人在 days 天内能获取的最大的利润

注:同一件商品可以反复买进和卖出


输入描述


3 第一行输入商品的数量 number
3 第二行输入商品售货天数 days
4 5 6 第三行输入仓库限制每件商品的最大持有数量是item[index]
1 2 3 第一件商品每天的价格
4 3 2 第二件商品每天的价格
1 5 3 第三件商品每天的价格


输入:
3
3
4 5 6
1 2 3
4 3 2
1 5 3


输出:
32

解题思路


由于题目比较复杂,为了降低难度,先不看示例case,假设有一件商品:

第 0 天的价格:1

第 1 天的价格:2

第 2 天的价格:3

第 3 天的价格:4

贪心算法的策略:由于不限制交易次数,只要今天价格比昨天高,就在昨天买,在今天卖。

比如上述商品,它的价格为 [1, 2, 3, 4] ,这 4 天的价格依次上升,按照贪心算法,得到的最大利润是:

res = (prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0]) = prices[3] - prices[0]


如果你读不懂上述例子,我们可以这么理解:第 0 天买, 第 1 天卖;第 1 天再买,第 2 天卖;第 2 天再买, 第 3 天卖;为什么这么操作?正如之前的贪心策略:只要今天价格比昨天高,就在昨天买,然后在今天卖。你可能会问:为什么不能在第 0 天买入,然后一直存放着不卖,直到第三天再卖出? 当然可以按照你的想法交易,但是我们的策略是不是等同于第 0 天买入,第 3 天卖出? 你可以自己计算一下,两种做法是不是最终的收益是一样的。

好了,当你理解了一件商品的买卖策略之后,多件商品的买卖策略完全相同。对于本题,多件商品,我们可以这么解题:

最开始,将最大利润设置为 0
然后遍历每件商品,计算利润。

  • 遍历每天的价格,计算该商品每天的利润当天价格 - 前一天价格的差值,如果差值为负数,则取0。
  • 将每天的利润累加,得到该商品总利润。
  • 计算该商品的最大利润,商品利润*仓库限制的最大持有数量
  • 将商品最大利润累加到总利润。

Java代码


import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 商品数量和售货天数
        int numberOfItems = Integer.parseInt(in.nextLine());
        int days = Integer.parseInt(in.nextLine());

        // 仓库限制的每件商品最大持有数量
        List<Integer> maxItemLimits = Arrays.stream(in.nextLine().split(" "))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 每件商品每天的价格
        List<ArrayList<Integer>> itemPrices = new ArrayList<ArrayList<Integer>>();
        for (int i = 0; i < numberOfItems; i++) {
            List<Integer> dailyPrice = Arrays.stream(in.nextLine().split(" "))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
            itemPrices.add(new ArrayList<>(dailyPrice));
        }

        // 最大利润
        int maxProfit = 0;
        
        for (int i = 0; i < itemPrices.size(); i++) {
            int profit = 0;
            for (int j = 1; j < itemPrices.get(i).size(); ++j) {
                profit += Math.max(0, itemPrices.get(i).get(j) - itemPrices.get(i).get(j - 1));
            }
            // 将商品利润累加到总利润
            maxProfit += profit * maxItemLimits.get(i);
        }

        System.out.println(maxProfit);
    }
}

Python代码


# coding:utf-8

import functools
# 商品数量
num_goods = int(input())

# 售货天数
num_days = int(input())

# 每种商品的最大持有数量
max_stock = [int(x) for x in input().split(" ")]

# 每种商品每天的价格
prices = []
for i in range(num_goods):
    prices.append([int(x) for x in input().split(" ")])

# 总利润
total_profit = 0

for i in range(len(prices)):
    profit = 0 
    for j in range(1, len(prices[i])):
        # 如果今天的价格高于昨天的价格,则买进昨天,今天卖出,获得利润
        # 如果今天的价格低于昨天的价格,那么就不操作,利润为0
        profit += max(0, prices[i][j] - prices[i][j-1])

    # 将每种商品的利润加入总利润
    total_profit += profit * max_stock[i]

print(total_profit)


C++代码


#include<iostream>
#include<vector>
using namespace std;

int main() {
    // 商品数量和经营天数
    int itemNum, days;
    cin >> itemNum >> days;

    // 每种商品的最大持有量
    vector<int> maxItem;
    for (int i=0; i<itemNum; i++) {
        int maxHold;
        cin >> maxHold;
        maxItem.push_back(maxHold);
    }

    // 每种商品每天的价格
    vector<vector<int>> prices;
    for (int i=0; i<itemNum; i++) {
        vector<int> price;
        for (int j=0; j<days; j++) {
            int p;
            cin >> p;
            price.push_back(p);
        }
        prices.push_back(price);
    }
    
    int maxProfit = 0;
    for (int i=0; i<prices.size(); i++) {
        int profit = 0;
        // 每天比较今天的价格与昨天的价格,如果今天价格高,则卖出商品获利
        for (int j=1; j<prices[i].size(); j++) {
            profit += max(0, prices[i][j] - prices[i][j-1]);
        }
        maxProfit += profit * maxItem[i];
    }
        
    cout << maxProfit << endl;

    return 0;
}

### 华为OD中的增强版 `strstr` 函数 #### 题目描述 题目要求实现一个增强版本的 `strstr` 函数,其功能是在源字符串中查找第一个匹配的目标字符串,并返回目标字符串首次出现位置相对于源字符串起始位置的偏移量。如果未找到,则返回 `-1`。此函数支持带有通配符模式的模糊查询。 #### 解题思路 为了处理带通配符的模糊查询,在遍历过程中需考虑多种情况: - 当前字符完全匹配; - 使用通配符代替任意单个字符; - 处理连续多个通配符的情况; 对于每种编程语言的具体实现方式有所不同,下面分别给出 C++Python 的解决方案[^1]。 #### C++ 实现方案 ```cpp #include <iostream> #include <string> using namespace std; int enhancedStrstr(const string& haystack, const string& needle) { int m = haystack.size(), n = needle.size(); for (int i = 0; i <= m - n; ++i) { bool match = true; for (int j = 0; j < n && match; ++j) { if (!(haystack[i + j] == '?' || needle[j] == '?' || haystack[i + j] == needle[j])) { match = false; } } if (match) return i; } return -1; } // 主程序用于读取输入并调用上述方法打印结果 int main() { string s, p; cin >> s >> p; cout << enhancedStrstr(s, p); } ``` #### Python 实现方案 ```python def enhanced_strstr(haystack: str, needle: str) -> int: m, n = len(haystack), len(needle) for i in range(m - n + 1): matched = True for j in range(n): if not any([ haystack[i+j] == ch or needle[j] == '?' for ch in [haystack[i+j], '?'] ]): matched = False break if matched: return i return -1 if __name__ == "__main__": source_string = input().strip() pattern_string = input().strip() result = enhanced_strstr(source_string, pattern_string) print(result) ``` 在实际考环境中需要注意的是,华为 OD 采用 ACM 模式进行考核,因此考生不仅需要完成核心算法逻辑的设计与编码工作,还需要自行负责数据的输入/输出操作部分[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AlgorithmHero

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值