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

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

#include <cstdlib>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.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_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<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;
}
/*
 
 
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值