题目描述:
商人经营一家店铺,有number种商品,由于仓库限制每件商品的最大持有数量是item[index],每种商品的价格在每天是item_price[item_index][day],通过对商品的买进和卖出获取利润,请给出商人在days天内能获取到的最大的利润;
注: 同一件商品可以反复买进和卖出;
输入描述:
3 // 输入商品的数量 number
3 // 输入商人售货天数 days
4 5 6 // 输入仓库限制每件商品的最大持有数量是item[index]
1 2 3 // 输入第一件商品每天的价格
4 3 2 // 输入第二件商品每天的价格
1 5 3 // 输入第三件商品每天的价格
输出描述:
32 // 输出商人在这段时间内的最大利润
补充说明:
根据输入的信息:
number = 3
days = 3
item[3] = {4,5,6}
item_price[3][4] = {{1,2,3},{4,3,2},{1,5,3}}
针对第一件商品,商人在第一天的价格是item_price[0][0] = 1时买入item[0]件,在第三天item_price[0][2] = 3的时候卖出,获利最大是8;
针对第二件商品,不进行交易,获利最大是0;
针对第三件商品,商人在第一天的价格是item_price[2][0] = 1时买入item[2]件,在第二天item_price[2][0] == 5的时候卖出,获利最大是24;
因此这段时间商人能获取的最大利润是8 + 24 = 32;
收起
示例1
输入:
3
3
4 5 6
1 2 3
4 3 2
1 5 3
输出:32
说明:示例2
输入:
1
1
1
1
输出:0
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int item = scan.nextInt();
int days = scan.nextInt();
int[] maxNum = new int[item];
int[][] arr = new int[item][days];
for (int i = 0; i < item; i++) {
maxNum[i] = scan.nextInt();
}
for (int i = 0; i < item; i++) {
for (int j = 0; j < days; j++) {
arr[i][j] = scan.nextInt();
}
}
int profit = 0;
for (int i = 0 ; i < item; i++) {
profit += helper(arr[i], maxNum[i]);
// System.out.println("current profit " + i + " is: " + profit);
}
System.out.print(profit);
}
public static int helper(int[] prices, int num) {
int min = prices[0];
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > min) {
profit += (prices[i] - min) * num;
min = prices[i];
} else {
min = prices[i];
}
}
return profit;
}
}