amazon 股票的最佳买入和卖出点

/* 
 * File:   stock_price.cpp
 * Author: hongbin
 * 给出一个股价序列,求出最佳的买入和卖出点, 也就是求序列后面的元素跟前面元素的最大值。
 */

#include 
#include 
#include 
#include 
#include 

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_diff1=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 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:"<

你可能感兴趣的:(网络编程,面试,c++)