121. Best Time to Buy and Sell Stock

来源:互联网 发布:sql server2012r2下载 编辑:程序博客网 时间:2024/06/06 01:54

标签(空格分隔): leetcode dp


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.

题意:
1. 说你有一个数组,第i个元素是第i天给定股票的价格。
2. 如果您只允许完成最多一笔交易(即买入一笔并出售该股票的一部分),
3. 设计一个算法来找到最大的利润。

例如:

例子一:Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)//例子二Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

说明:
1. 寻找一个序列中升序序列的最小最大值;
2. 分解子问题: 两个值的差
状态方程:

profit = max(profit, right -left);//利益取大的left = min(left,right);//最小值取两个里面最小的

代码:

int maxProfit(vector<int>& prices) {    int len = prices.size();    if (len < 2)        return 0;    int minp = prices[0];    int profit = 0;    for (int i = 1; i < len; ++i)    {        profit =max(profit, prices[i] - minp);        minp = min(minp, prices[i]);    }    //cout << "min: " << minp << " maxp: " << profit << endl;    return profit;}
原创粉丝点击