zoukankan      html  css  js  c++  java
  • 【Best Time to Buy and Sell Stock】cpp

    题目:

    Say you have an array for which the ith 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.

    代码:

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
                if (prices.size()==0) return 0;
                int min_price = prices[0], max_profit = 0;
                for ( size_t i = 0; i < prices.size(); ++i )
                {
                    min_price = std::min(min_price, prices[i]);
                    max_profit = std::max(max_profit, prices[i]-min_price);
                }
                return max_profit;
        }
    };

    tips:

    Greedy

    核心在于维护两个变量:

    min_price: 算上当前元素的最小值

    max_profit:算上当前元素的最大利润

    走完所有元素,可以获得max_profit

    ================================================

    第二次过这道题,犹豫了一下才想起来思路。

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
                int globalProfit = 0;
                if ( prices.empty() ) return globalProfit;
                int minPrice = prices[0];
                for ( int i=1; i<prices.size(); ++i )
                {
                    minPrice = min(minPrice, prices[i]);
                    globalProfit = max(globalProfit, prices[i]-minPrice);
                }
                return globalProfit;
        }
    };
  • 相关阅读:
    自动删除几天前的备份集文件脚本 for windows
    Oracle备份脚本(数据泵)-Windows平台
    机器学习常用python包
    AI summary
    git 设置
    mystar01 nodejs MVC gulp 项目搭建
    electron搭建开发环境
    AI ubantu 环境安装
    xtrabackup原理
    xtrabackup 安装
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4539811.html
Copyright © 2011-2022 走看看