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

    Dynamic Programming

    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.

    C++代码实现:

    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Solution
    {
    public:
        int maxProfit(vector<int> &prices)
        {
            if(prices.empty())
                return 0;
            int buy=prices[0];
            int maxSum=0;
            int sum=0;
            int i;
            for(i=1;i<(int)prices.size();i++)
            {
                sum=prices[i]-buy;
                if(sum>maxSum)
                    maxSum=sum;
                if(prices[i]<buy)
                    buy=prices[i];
            }
            return maxSum;
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> vec={1,4,6,8,3,5,9,3,6};
        cout<<s.maxProfit(vec)<<endl;
    }
  • 相关阅读:
    各职业岗位说明
    感慨集中所
    批量插入测试数据
    写作技巧
    Cordova学习
    CocoStudio
    maven使用感受
    org.json
    ApplicationContext
    2017
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4113447.html
Copyright © 2011-2022 走看看