
Problem Description:
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.
题目大意:
有一个数组表示一段时间内某只股票每天的价格,如果你只能买卖一次,求你能获得的最大利润
Solutions:
依次找到最小值,然后再记录最大差值,返回最大差值即可。
Code in C++:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<2) return 0;
vector<int>dp(prices.size(),0);
int max=INT_MIN;
int min=prices[0];
for(int i=1;i<prices.size();i++)
{
if(prices[i]<min) min=prices[i];
dp[i]=prices[i]-min;
if(dp[i]>max)
max=dp[i];
}
return max;
}
};




近期评论