LeetCode - Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝怎么推广 编辑:程序博客网 时间:2024/04/30 06:42
public class Solution {    public int maxProfit(int[] prices) {        // Start typing your Java solution below        // DO NOT write main() function        if (prices.length < 1)            return 0;        int[] lowest = new int[prices.length];        int[] highest = new int[prices.length];        int min = prices[0];        for (int i=0; i<prices.length; i++) {            min = Math.min(min, prices[i]);            lowest[i] = min;        }        int max = prices[prices.length-1];        for (int i=prices.length-1; i>=0; i--) {            max = Math.max(max, prices[i]);            highest[i] = max;        }        max = 0;        for (int i=0; i<lowest.length; i++)            max = Math.max(max, highest[i]-lowest[i]);                return max;    }}


第一题很简单,时间复杂度为 O(N)

原创粉丝点击