zoukankan      html  css  js  c++  java
  • LeetCode_Best Time to Buy and Sell Stock

    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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(prices.size() <2) return 0;
            int min ,current, profit = 0;
            
            min = prices[0] ;
            
            for(int i = 1;i < prices.size();i++)
            {
                current = prices[i];
                if(min< current)
                 profit = max(profit, current - min);
                 else if(min > current)
                   min = current ;
            }
            
            return profit;
        }
    };

     

    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    vue 中简单路由的实现
    Vue中对生命周期的理解
    内存泄漏
    前端工程化
    exports 和 module.exports 的区别
    Nodejs的url模块方法
    MongoDB 的获取和安装
    Anjular JS 的一些运用
    移动端vconsole调试
    安装fiddler时,电脑浏览器没网
  • 原文地址:https://www.cnblogs.com/graph/p/3011923.html
Copyright © 2011-2022 走看看