title | date | tags | mathjax |
---|---|---|---|
以逗号为分隔符输入一个整型数组 |
2019-08-06 04:44:14 -0700 |
C++ |
true |
假如一个数组中存储股票在一天交易窗口各时间点的股票价格(正整数)。允许任意次数买入卖出,请提供一个算法,计算通过买卖可能导致的最大亏损。
输入描述:
股票价格序列,序列长度不超过100,请用逗号隔开。
输出描述:
最大的可能损失。
示例1:
输入:
100,180,310,40,535,695
输出:
270
示例2:
输入:
100,180,0,310,40,535,695
输出:
450
说明:
180买入,0卖出;310买入,40卖出
#include <iostream>
#include <string>
#include <vector>
#include "stdio.h"
using namespace std;
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1)
return 0;
int maxprices = -1;
int minprices = -1;
int i = 0;
int res = 0;
if (prices[i] > prices[i + 1])
maxprices = prices[i];
for (i = 1; i < prices.size()-1; i++)
{
if (prices[i - 1] < prices[i] && prices[i] > prices[i + 1])
maxprices = prices[i];
if (prices[i - 1] > prices[i] && prices[i] < prices[i + 1])
minprices = prices[i];
if (maxprices != -1 && minprices != -1) {
res += (maxprices - minprices);
maxprices = minprices = -1;
}
}
if (prices[i] < prices[i - 1] && maxprices != -1)
res += (maxprices - prices[i]);
return res;
}
int main()
{
string s;
cin >> s;
vector<int>nums;
char *str = (char *)s.c_str();//string --> char
const char *split = ",";
char *p = strtok(str, split);//逗号分隔依次取出
int a;
while (p != NULL) {
sscanf(p, "%d", &a);//char ---> int
nums.push_back(a);
p = strtok(NULL, split);
}
for (int i = 0; i < nums.size(); i++) {
printf("%d ", nums[i]);
}
printf("\n");
cout << maxProfit(nums) << endl;
}