您的位置:首页 > 其它

LeetCode Best Time to Buy and Sell Stock(dp)

2016-01-23 21:20 267 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: