Given an array of integers, eg. [ 9 8 7 6 2 3 4 3 2 7 8] I want to traverse through the array containing stocks so i can buy and sell as many stocks as I can to get the maximum profit. for example, from the above array: Buy when stock is 2 sell when stock is 4 buy when stock is 2 sell when it's 8 total profit= 6+2 = 8
The logic I used is that if the stock is lower than the two adjacent ones, we buy it and when it's higher than the adjacent two, we sell it. Here's my code in C++ but it doesn't seem to work:
int buy = 0;
int sell = 0;
int total_profit = 0;
for(int k=0; k<= (length); k++){
if ((k == 0)){
sell=0;
}
if( (k != 0) && (arr[k]>arr[k-1]) && (arr[k]>arr[k+1]) && (k != length)){
sell=arr[k];
cout<<"sell "<< sell<<" ";
}
if( (k=length) && (arr[k] >arr[k-1])){
sell=arr[k];
cout<<"sell "<< sell<<" ";
}
if ((k == 0) && (arr[k]<arr[k+1])){
buy=arr[k];
cout<<"buy "<<buy<<" ";
}
if( (k != 0) && (arr[k]<arr[k-1]) && (arr[k]<arr[k+1]) && (k != length)){
buy=arr[k];
cout<<"buy "<<buy<<" ";
}
if( (k=length) && (arr[k] <arr[k-1])){
buy=arr[k];
cout<<"buy "<<buy<<" ";
}
if ((buy != 0) && (sell != 0)){
int prof= sell - buy;
buy=0;
sell=0;
total_profit += prof;
}
}
I can't seem to figure out the problem(aside from bad syntax), and I'd love some help!
Aucun commentaire:
Enregistrer un commentaire