[LeetCode] Best Time to Buy and Sell Stock

来源:互联网 发布:js验证密码的正则 编辑:程序博客网 时间:2024/04/28 14:37

题目:

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.

解析:

数组右边的数减去左边的数的数对之差最大。

动态规划求解

maxDiff[i] >= prices[j] - prices[i] (j>i)
maxDiff = max( maxDiff, maxMinuend-cur )

class Solution {public:int maxProfit(vector<int> &prices) {if(prices.size()<2)return 0;int length = prices.size();int max = prices.back();int maxDiff = max-prices[length-2]>0?max-prices[length-2]:0;for(int i = length-3;i>=0;i--){if(prices[i+1]>max){max=prices[i+1];}int curDiff= max-prices[i];if(curDiff>maxDiff)maxDiff=curDiff;}return maxDiff;}};




0 0
原创粉丝点击