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) {
            if(prices.size() <= 0)
                return 0;
            int min = prices[0];
            int profit = 0;
            for(vector<int>::iterator vit = prices.begin();vit != prices.end();vit++)
            {
                profit = Max (*vit - min,profit);
                if(*vit < min)
                {
                    min = *vit;
                }

            }
            return profit;
        }
       
        int Max(int a,int b)
        {
            return a > b ? a : b;
        }
    };

  • 相关阅读:
    poj 2485 Highways 最小生成树
    hdu 3415 Max Sum of MaxKsubsequence
    poj 3026 Borg Maze
    poj 2823 Sliding Window 单调队列
    poj 1258 AgriNet
    hdu 1045 Fire Net (二分图匹配)
    poj 1789 Truck History MST(最小生成树)
    fafu 1181 割点
    减肥瘦身健康秘方
    人生的问题
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5425087.html
Copyright © 2011-2022 走看看