* * * * File:stock_price.cpp * Author:hongbin * gives a stock price sequence to find the best buy and sell point, that is, after the sequence of elements with the maximum value of the preceding elements. * #include <cstdlib> #include <iostream> #include <string.h> #include <stdlib.h> #include <s
Tdio.h> using namespace std; O (n^2) bool Find_max_profit1 (int stock_price[], int length, int& buy_index, int &sell_index) {int Max_profit
= 0;
int end=length-1;
int price_diff1=0;
BOOL Find=false;
buy_index=sell_index=0;
if (length <2) return find;
MAX_PROFIT=STOCK_PRICE[1]-STOCK_PRICE[0]; for (int index=0; index < length-1. index++) for (int step=index+1;step < length; step++) {Price_diff
1=stock_price[step]-stock_price[index];
if (price_diff1>max_profit) {max_profit= price_diff1;
Buy_index=index;
Sell_index=step;
Find=true;
} return find; }//o (N) bool Find_max_profit2 (int stock_price[], int length, int& buy_index, int &sell_index) {int max_profit=0;
int end=length-1;
int price_diff1=0,price_diff2=0;
BOOL Find=false;
buy_index=sell_index=0;
if (length <2) return find;
MAX_PROFIT=STOCK_PRICE[1]-STOCK_PRICE[0];
for (int index=0; index<end; index++) {price_diff1=stock_price[index+1]-stock_price[index];
PRICE_DIFF2=STOCK_PRICE[INDEX+1]-stock_price[buy_index];
if (Price_diff2 > Max_profit) {sell_index = index+1;
MAX_PROFIT=PRICE_DIFF2;
Find=true;
} if (price_diff1 >max_profit) {buy_index=index;
Sell_index = index+1;
max_profit=price_diff1;
Find=true;
} return find;
}/* */int main (int argc, char** argv) {int price[]={2,5,3,4,1,25,1,8,9};
int buy_index=0;
int sell_index=0;
Find_max_profit2 (Price,9,buy_index,sell_index); cout<< "Find_max_profit_good find:buy index:" <<buy_index+1<< "sell index:" <<SELL_INDEX+1≪<endl;
cout<< "Profit is:" << (Price[sell_index]-price[buy_index]) <<endl;
buy_index=sell_index=0;
Use another algorithm to do again find_max_profit1 (Price,9,buy_index,sell_index); cout<< "find_max_profit1:: Buy Index:" <<buy_index+1<< "sell index:" <<sell_index+1<<
Endl
cout<< "Profit is:" << (Price[sell_index]-price[buy_index]) <<endl;
return 0; }
/*
*/