Best-time-to-buy and-sell-stock

(解二最优,我现在能写的最好的了) 

题目:

Say you have an array for which the i th 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

 解一:

public class Solution {
    public int maxProfit(int[] prices) {
        int max = 0, temp = 0 , i = 0 , j = 0;
        for(i = 0; i < prices.length-1; i++){
            for(j = i; j < prices.length-1 ; j++){
                temp = prices[j+1] - prices[i];
                if(temp>max){
                    max = temp; 
                }
            }
        }
        return max;
    }
}

  

解二:

  

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

  

解三:

public class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0; i < prices.length-1; i++){
            for(int j = i; j < prices.length-1 ; j++){
                if(prices[j+1] - prices[i]>max){
                    max = prices[j+1] - prices[i]; 
                }
            }
        }
        return max;
    }
}

  

原文地址:https://www.cnblogs.com/xww115/p/11174019.html