【发布时间】:2014-11-12 17:32:15
【问题描述】:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/* Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.
每天,您可以购买一股 WOT,出售您拥有的任意数量的 WOT,或者根本不进行任何交易。通过最佳交易策略,您可以获得的最大利润是多少? */
struct data{
int index;
long value;
};
bool comp(const data &a,const data &b)
{
return a.value > b.value;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
long n;
int i,j;
cin>>t;
while(t)
{
t=t-1;
cin>>n;
long arr[n];
long buy=0,sell=0;
long buy_count=0;
vector<data> copy;
long max = 0;
int indix=0;
for(i=0;i<n;i++)
{
cin>>arr[i];
//copy[i] = arr[i];
data s;
s.index = i;
s.value = arr[i];
copy.push_back(s);
}
//sort to get the maximum elements and their positions at the top
sort(copy.begin(),copy.end(),comp);
//cout<<copy[0].value;
max = copy[0].value;
indix = copy[0].index;
int c=0;
for(i=0;i<n;i++)
{
if(i<indix)
{
//buy a share
buy+=arr[i];
buy_count+=1;
}
else if(i==indix && i!=0)
{
//time to sell
sell+= buy_count*(arr[i]);
cout<<"in sell : sell :"<<sell<<endl;
c++;
cout<<"hello";// not printing , giving runtime error over here
buy_count = 0;
while(i>copy[c].index)
{
c++;
}
cout<<"hello";
max = copy[c].value;
indix = copy[c].index;
}
}
cout<<(sell-buy)<<endl;
}
return 0;
}
【问题讨论】:
-
你有什么问题?
-
StackOverflow 不是一个家庭作业帮助网站。请就您在使用此代码时遇到的问题提出具体问题,而不是要求我们为您解决问题。
-
了解如何创建动态大小的数组或如何使用
std::vector。最好两者都有。 -
您使用的是什么平台?
long arr[n];不是有效的 C++ 代码。 -
cin>>n; long arr[n];在 C 中有效,并且作为 C++ 的一些编译器扩展。当您已经在使用std::vector时,为什么还要使用原始数组?