121. Best Time to Buy and Sell Stock

来源:互联网 发布:js打开网页弹出提示框 编辑:程序博客网 时间:2024/05/16 05:03

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 1

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

Solution 2 Optimization 

//Optimization on the first onepublic int maxProfit3(int[] prices) {    if(prices == null || prices.length < 2) return 0;          int maxProfit = 0, minPrice = prices[0];    for(int i = 1; i < prices.length; i++) {        if(prices[i] > prices[i - 1]) {            maxProfit = Math.max(maxProfit, prices[i] - minPrice);               } else {             minPrice = Math.min(minPrice, prices[i]);        }    }    return maxProfit;}

Solution 3

// O(N * N)public static int maxProfit2(int[] prices) {if (prices.length < 2)return 0;int diff[] = new int[prices.length - 1];for (int i = 1; i < prices.length; i++) {diff[i - 1] = prices[i] - prices[i - 1];}return maxSubArray(diff);}public static int maxSubArray(int[] nums) {if (nums.length < 1)return 0;int preMax = 0, max = 0;for (int i = 0; i < nums.length; i++) {max = Math.max(max, preMax + nums[i]);preMax = Math.max(0, preMax + nums[i]);}return max;}


0 0