买卖股票问题

简介: 买卖股票问题

1、问题如下:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。(先买入,后卖出)

2、代码如下:

#include <bits/stdc++.h>
using namespace std;
#define N 10000
int n=0;//记录股票价格的天数 
int MinLeft=0;//此天之前的最小值
int MaxRight=0;//记录此天以及此天之后股票的最大值
int profit=0;//记录每次计算的利润值 
int MaxProfit=0;//记录最大利润 
int price[N]={0};//记录股票各天的价格 
void input(){//输入 
  for(int i=1;i<N;i++){
    cin>>price[i];//输入股票价格 
    n++;//股票价格的天数+1 
    if(getchar()=='\n') break;//输入回车,则结束 
  } 
} 
void input1(){
  n=6;
  for(int i=1;i<=n;i++){
    cin>>price[i];
  }
} 
void print(){
  for(int i=1;i<=n;i++){//从第二天开始 
    cout<<price[i]<<" ";
  }
} 
void begin(){//初始化 
  MinLeft=price[1];//MinLeft为第一天价格 
  for(int i=2;i<=n;i++){//MaxRight为第二天以及第二天之后的最大价格 
    if(price[i]>MaxRight) MaxRight=price[i];
  }
  profit=MaxRight-MinLeft;
  MaxProfit=profit;
  //cout<<MinLeft<<" "<<MaxRight<<" "<<MaxProfit<<endl;
} 
void compute(){//计算更新 
  for(int i=2;i<=n;i++){
    if(MinLeft>price[i]) MinLeft=price[i];
    if(MaxRight==price[i]){
      MaxRight=price[i+1]; 
      for(int j=i+2;j<=n;j++){//MaxRight为第二天以及第二天之后的最大价格 
        if(price[j]>MaxRight) MaxRight=price[j];
      }
    }
    profit=MaxRight-MinLeft;
    if(profit>MaxProfit) MaxProfit=profit;
  }
}
int main(){
  input1(); 
  begin(); 
  compute();
  if(MaxProfit> 0) cout<<MaxProfit<<endl;
  //print();打印股票价格 
  return 0;
}

image.gif

3、示例

输入:

7 1 5 3 6 4
image.gif

输出:

5
image.gif

输入:

6 5 4 3 2 1
image.gif

输出:

(没有输出)
image.gif
目录
相关文章
|
9月前
|
算法
【动态规划刷题 7】 买卖股票的最佳时机含冷冻期&& 买卖股票的最佳时机含手续费
【动态规划刷题 7】 买卖股票的最佳时机含冷冻期&& 买卖股票的最佳时机含手续费
|
18天前
leetcode-714:买卖股票的最佳时机含手续费
leetcode-714:买卖股票的最佳时机含手续费
22 0
|
18天前
|
算法
leetcode121. 买卖股票的最佳时机
leetcode121. 买卖股票的最佳时机
16 0
|
18天前
|
算法 C++
买卖股票的最佳时机(C++)
买卖股票的最佳时机(C++)
22 0
|
18天前
|
算法
leetcode-121:买卖股票的最佳时机
leetcode-121:买卖股票的最佳时机
27 0
|
8月前
|
算法
【学会动态规划】买卖股票的最佳时机含手续费(16)
【学会动态规划】买卖股票的最佳时机含手续费(16)
17 0
|
10月前
|
算法
买卖股票系列
买卖股票系列
48 0
|
12月前
|
算法
买卖股票的最佳时机II
买卖股票的最佳时机II
46 0
|
算法
leetcode 714 买卖股票的最佳时机含手续费
leetcode 714 买卖股票的最佳时机含手续费
71 0
leetcode 714 买卖股票的最佳时机含手续费
|
算法
LeetCode 122. 买卖股票的最佳时机 II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
62 0

热门文章

最新文章