Best Time to Buy and Sell Stock

来源:互联网 发布:工业设计软件 编辑:程序博客网 时间:2024/06/08 07:11

题目名称
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.

分析
  题目中明确说了只能进行一次买卖交易,也就是说只能买一次,卖一次。其实就是找出差距最大的两天的价格差(后面的价格比前面的高)。

C++代码

class Solution {public:    int maxProfit(vector<int>& prices) {        int size = prices.size();        if(size==0 || size==1)            return 0;        int maxPro=0,minPrice=prices[0];        for(int i=1;i<size;i++){            minPrice=min(minPrice,prices[i]);            maxPro=max(maxPro,prices[i]-minPrice);        }        return maxPro;    }};

总结
  一个比较简单的动态规划问题。

0 0