暴力方法时间复杂度超出 贪心算法,循环一次,若有最小的价格记录最小价格。没有最小价格判断收益是否大于res,大于则记录res。最后返回res

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        /*int max = 0;
        //int[][] dp = new int[prices.length+1][prices.length+1];
        for(int i = 0; i<prices.length; i++){
            for(int j = i;j<prices.length; j++){
                //dp[i][j] = prices[j] - prices[i];
                if(prices[j] - prices[i] > max){
                    max = prices[j] - prices[i];
                }
            }
        }
        return max;*/
        int minPrices = Integer.MAX_VALUE;
        int res = 0;
        for(int i = 0;i<prices.length;i++){
            if(prices[i]<minPrices){
                minPrices = prices[i];
            }
            else if(prices[i] - minPrices > res){
                res = prices[i] - minPrices;
            }
        }
        return res;
    }
}