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.
比原来少一次循环
class Solution {
public:
int maxProfit(vector<int> &prices) {
if( prices.size() < 2)
return 0;
vector< int> dp( prices.size(), INT_MAX);
int max_profit = INT_MIN;
dp[0] = prices[0];
for( int i = 1; i < prices.size(); ++i){
dp[i] = min( dp[i-1], prices[i]);
max_profit = max_profit > prices[i] - dp[i] ? max_profit : prices[i] - dp[i];
}
return max_profit;
}
};
一维动态规划:dp[i]保存当前下标之前的最低股价
dp[i] = min( dp[i-1], prices[i]);
代码中注释掉部分的解法会TLE,后来发现二了,只要比较dp[i-1]和当前值的大小就够了,速度快很多,时间复杂度从O(n2)变为O(n)
class Solution {
public:
int maxProfit(vector<int> &prices) {
if( prices.size() < 2)
return 0;
vector< int> dp( prices.size(), INT_MAX);
dp[0] = prices[0];
for( int i = 1; i < prices.size(); ++i){
//int min = INT_MAX;
//for( int j = i; j >= 0; --j){
// min = min < prices[j] ? min : prices[j];
//}
dp[i] = min( dp[i-1], prices[i]);
//dp[i] = min;
}
int max_profit = INT_MIN;
for( int i = 0; i < prices.size(); ++i)
max_profit = max_profit > ( prices[i] - dp[i]) ? max_profit : prices[i] - dp[i];
return max_profit;
}
};