美文网首页
股票最大利润 I

股票最大利润 I

作者: 静水流深ylyang | 来源:发表于2018-12-04 23:21 被阅读0次

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


  • 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
欢迎来踩~~~~


相关文章

  • 股票最大利润 I

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

  • 算法笔记

    Array 最大收益 假设您有一个数组,其中第i个元素是第i天给定股票的价格。设计一个算法来找到最大的利润。您可以...

  • Java日记2018-07-05

    n 个骰子的点数dp[i][j] 表示前 i 个骰子产生点数 j 的次数 扑克牌顺子 股票的最大利润 求 1+2+...

  • 63 股票最大利润

    动态追踪当前最小值,当前最大利润和全局利润对比

  • 股票最大利润 II

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

  • 股票的最大利润

    题目链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-l...

  • 面试题63. 股票的最大利润

    股票的最大利润 题目描述 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多...

  • Leetcode.122.Best Time to Buy an

    题目 求股票获取最大利润, 可以进行多次交易.给定一个数组, 数组表示第i天的股票价格. 买进后一天才能卖出, 卖...

  • 121. Best Time to Buy and Sell S

    给一个数组,其中第 i 个元素是第 i 天的股票价格,假设只能完成一笔交易,找出最大利润。注: 买入之前不可卖出。...

  • Java日记2018-05-23

    今天算是个里程碑了 第一题 股票的最大利润使用贪心策略,假设第 i 轮进行卖出操作,买入操作价格应该是 i 之前并...

网友评论

      本文标题:股票最大利润 I

      本文链接:https://www.haomeiwen.com/subject/gjsbcqtx.html