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:
    //I
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int len = prices.size();
            if(len < 2) return 0;
            
            int min = prices[0];
            int res = 0;
            for(int i = 1; i< prices.size(); ++i)
            {    
                if(prices[i] < min){
                    min = prices[i] ;
                    continue;
                }
                res = res > prices[i] - min ? res : prices[i] - min ;
            }
            
            return res;
        }
    };
  • 相关阅读:
    jsp4个作用域
    jsp9个内置对象
    jsp指令
    jsp注释
    jsp原理
    java面试
    代理
    泛型
    exception
    基础
  • 原文地址:https://www.cnblogs.com/graph/p/3319423.html
Copyright © 2011-2022 走看看