股票最大利润 I

  • Best Time To Buy and Sell Stock
    Say you have an array for which the i th element is the price of a given stock on day i.
    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

  • 题目大意:给定一个数组,第i个元素代表第i天股票的价格,只限一次买入和卖出,求最大收益。

  • 思路:找最低的价格,和它之后的最高价格,求差,再和已有的最大利润比较。不同于股票最大利润 II。在这个问题中,按那种思路找到的只是局部最大利润。

  • 代码:

#include<iostream>
#include<vector>
using namespace std;
int maxProfit(vector<int> &prices)
{
    // 价格数要大于等于两个才能考虑(重要)
    if(prices.size() < 2)return 0;
    int max_profit = 0;
    int min_price = prices.front();
    vector<int>::iterator it;
    for(it = prices.begin()+1; it != prices.end(); it++)
    {
        // 比较寻找最低利润
        min_price = min_price < *it ? min_price : *it;
        // 跟当前已找到的最高利润作比较
        max_profit = max_profit > (*it - min_price) ? max_profit : (*it - min_price);
    }
    return max_profit > 0 ? max_profit : 0;
}
int main()
{
    vector<int> prices;
    for(int i = 0; i < 10; i++)
    {
        int a;
        cin >> a;
        prices.push_back(a);
    }
    cout << maxProfit(prices) << endl;
    return 0;
}
  • 以上。

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值