面试题63:股票的最大利润
文章目录
题目
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
考点
动态规划
LeetCode版本
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty())return 0;
int min = prices[0];
int len = prices.size();
vector<int> dp(len,0);
dp[0] = 0;
for(int i = 1; i< len; i++ ){
if(prices[i] < min) min = prices[i];
dp[i] = max(dp[i-1],prices[i]-min);
}
return dp[len-1];
}
};