Simple Java O(n) solution


  • 0
    V

    I simply scan the array from the end to the beginning, updating a value that is the max from i to N-1. I then update the max_difference value and return it.

    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0;
            int max_diff = 0;
            for (int i = prices.length - 1; i >= 0; i--) {
                if (prices[i] > max) {
                    max = prices[i];
                }
                
                int diff = Math.abs(max - prices[i]);
                
                if (diff > max_diff) {
                    max_diff = diff;
                }
            }
            
            return max_diff;
        }
    }
    

Log in to reply
 

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