Best Time to Buy and Sell Stock

来源:互联网 发布:mac无线鼠标没反应 编辑:程序博客网 时间:2024/06/03 17:05

一道很好的题,career cup上有一道facebook的题和这个一模一样: Given an array, find the maximum difference between two array elements given the second element comes after the first. 

解法是保存数组中发现的最小值,每发现当前的值比最小值大,再看这个差值和diff谁大,保存最大的diff,继续移动。所以这是一个O(N)的算法。O(N*N)的算法是所有的的元素都做减法,保留最大的diff,就不写了。


public int maxProfit(int[] prices) {        int diff = 0;        int minV = Integer.MAX_VALUE;        for (int i = 0; i < prices.length; i++){            if(prices[i] < minV) minV = prices[i];            if(prices[i] > minV) {                diff = Math.max(prices[i] - minV, diff);            }        }        return diff;    }


0 0