您的位置:首页 > 其它

LeetCode Best Time to Buy and Sell Stock

2015-07-07 14:36 323 查看
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.
Solution:
题目的意思理解了我半天。

就是给定一个股票的数组,要求如何使得赚取的股票利润最大。也就是最大值减去最小值。

但是注意一点,股票是有时间的,从正过来的顺序,复杂度是O(n^2),但是按照时间反过来的顺序,可以降一维的复杂度,变成O(n)。

import java.util.*;

public class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0)
return 0;
int max = 0, maxPrice = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
maxPrice = Math.max(maxPrice, prices[i]);
max = Math.max(max, maxPrice - prices[i]);
}

return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: