粮油买卖 | 时间限制:1秒 | 内存限制:262144K
贩卖粮油的小华在经营一段时间后,发现和旁边的商贩相比,利润较低,于是开始记录3,4月份自己经营的粮油价格,以便第二年进行参考,请你写个程序帮他计算一下,在一段周期内,买卖粮油可能获得的最大利润是多少?
备注:
我们使用数组来存储小华记录的数据,具有有序性;
示例1
键盘输入
[7,1,5,3,6,4]
输出
5
说明
价格为1时进货,为6时贩卖,可以达到利润最大5,注意时间(数组)有序
示例2
键盘输入
[7,6,4,3,1]
输出
0
- #include
- #include
- #include
- #include
- using namespace std;
-
- int main() {
- string input_str;
- getline(cin, input_str);
-
- // 以逗号分隔读入数字,存储到 vector 中
- vector<int> prices;
- char* p = strtok(const_cast<char*>(input_str.c_str()), "[,]");
- while (p) {
- prices.push_back(atoi(p));
- p = strtok(nullptr, "[,]");
- }
-
- // 计算最大利润
- int profit = 0;
- int min_price = prices[0];
- for (int i = 0; i < prices.size(); i++) {
- min_price = min(min_price, prices[i]);
- profit = max(profit, prices[i] - min_price);
- }
-
- cout << profit << endl;
-
- return 0;
- }
-
-