每日一题-数组 *leetcode121

135 阅读1分钟

一、题目描述

二、题目理解

  1. 可以使用暴力解法,但时间复杂度为O(n^2);
  2. 使用一次遍历的方法,如果当前元素比最低点小的话,即可设为新的最低点;否则的话,如果当前元素卖出大于截至目前的最大利润的话,则更新最大利润。
  3. 复习用户输入。

三、 优解代码

import java.util.Scanner;   
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit =0;
        for(int i =0;i<prices.length;i++){
            if(prices[i]<minPrice){
                minPrice = prices[i];
            }else if(prices[i] - minPrice > maxProfit){
                maxProfit = prices[i]- minPrice;
            }
        }
        return maxProfit;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入股票数值数组:");
        String[] string = sc.nextLine().split(" ");
        int[] prices = new int[string.length];
        for(int i =0;i<prices.length; i++){
            prices[i] = Integer.parseInt(string[i]);
        }
        Solution solution = new Solution();
        int result = solution.maxProfit(prices);
        System.out.println("result:"+ result);
    }
}

四、存在问题

  1. sc.nextLine()nextLine是方法,调用需要加括号;
  2. 一次遍历的一个逻辑思路在于:如果当前元素不是最低点,则可以判断是否达到最大收益(最低点一定不可能达到最大收益)。