Simple solution using Java with o(3n)time complexity!


  • 1
    X
    public class Solution {
        public int maxProfit(int[] prices) {
            int length=prices.length;
            int []max=new int[length];
            int []min=new int[length];
            int minnum=Integer.MAX_VALUE,maxnum=Integer.MIN_VALUE,result;
            for(int i=0;i<length-1;i++)
            {
                if(prices[i]<minnum){
                    minnum=prices[i];
                }
                min[i]=minnum;
            }
            
            for(int i=length-2;i>=0;i--)
            {
                if(prices[i+1]>maxnum){
                    maxnum=prices[i+1];
                }
                max[i]=maxnum;
            }
            result=0;
            for(int i=0;i<length-1;i++)
            {
                if(max[i]-min[i]>result)
                    result=max[i]-min[i];
            }
            return result;
        }
    }

  • 0
    S

    Use this as reference.


  • 0
    Y

    Hey, body. There is no need using max variable.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.