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.
题意:给出一个数组,每个元素表示股票在第i天的价钱
思路:用动态规划。用dp(i)表示从第i个到第n天的最大的价钱,状态转移方程为dp(i) = max{dp(i +1),price[i]}
代码如下:
class Solution
{
public int maxProfit(int[] prices)
{
int len = prices.length;
if (0 == len) return 0;
int ans = 0;
int max = prices[len - 1];
for (int i = len - 1; i >= 0; i--)
{
ans = Math.max(max - prices[i], ans);
if (prices[i] > max)
{
max = prices[i];
}
}
return ans;
}
}