leetcode array|121. Best Time to Buy and Sell Stock

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

随之日期的增长,找出两天之间最大的差值。

最开始的想法是记录low和high这两个下标,不断向前推进,或者是使用栈或者是队列之类的数据结构,但实现过程中出了点问题,最后选择了暴力算法——两层循环嵌套,时间复杂度居然没有超!

class Solution {
    public int maxProfit(int[] prices) {
        int profit=0;
        int high,low;
        for(int i=0;i<prices.length;i++){
            high=prices[i];
            low=prices[0];
            for(int j=0;j<i;j++){
                low=Math.min(low,prices[j]);
            }
            profit=Math.max(profit,high-low);
        }
        return profit;
    }
}

应该还是有速度更快的方法的!


果真自己是笨蛋。其实只需要遍历一遍,记录好当前元素之前的最小值即可,自己一直在想着两个指针这种情况,思维被禁锢住了。

class Solution {
    public int maxProfit(int[] prices) {
        //所以其实onepass的话是不需要记录最大值的位置的 唔 智障
        int lowPrice=Integer.MAX_VALUE;
        int profit=0;
        for(int i=0;i<prices.length;i++){
            lowPrice=Math.min(lowPrice,prices[i]);
            profit=Math.max(profit,prices[i]-lowPrice);
        }
        return profit;
    }
}

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/81118713
今日推荐