我的c ++代码中有一个奇怪的错误

时间:2015-11-12 00:13:35

标签: c++ vector

我们的教授希望我们写一些代码来做一些关于金融工具的计算,买入低价并卖出高价。价格会随着时间而变化。例如,输入为{1,2,4},因此我们可以买1卖2卖,买2卖4.所以输出应该是1 + 2 = 3。如果输入是{4,2,1},我们就无法买入低价并卖出高价。所以输出应该是0。 这是我的代码。

#include<iostream>
#include<vector>

using namespace std;

int getMaxProfit(vector<int> &prices)
 {
int p;
int n=0;
vector<int> profits;

if(prices.size()==1)
{
    return 0;
}

for(int i=0; i<prices.size();i++)
{
    if (prices[i]<prices[i+1])
    {
        p=prices[i+1]-prices[i];
        profits.push_back(p);
    }

}

for(int i=0; i<profits.size();i++)
{
    n=n+profits[i];

}


return n;
}

int main()
{
vector<int> prices = {1,2,4};

cout<<getMaxProfit(prices);

return 0;
}

当我输入的值只有4或更少时,它的效果非常好。但是,如果有超过4个值,例如{1,1,2,3,4}。我会得到错误的答案。我无法弄清楚它有什么问题。

1 个答案:

答案 0 :(得分:2)

好的,我明白了。改变了一些关于我的代码并且它有效。

#include<iostream>
#include<vector>

using namespace std;

int getMaxProfit(vector<int> &prices)
{
int p;
int n=0;
vector<int> profits;

if(prices.size()==1)
{
    return 0;
}
p = prices[0];
for(int i=1; i<prices.size();i++)
{
    if (p<prices[i])
    {
        n=prices[i]-p;
        profits.push_back(n);
        p=prices[i];
    }
    else
    {
        p =prices[i];
    }
}
n=0;

for(int i=0; i<profits.size();i++)
{
    n=n+profits[i];

}


return n;
}

int main()
{
vector<int> prices = {3,1,5,2,4};

cout<<getMaxProfit(prices);

return 0;
}