O(n) | Using Max and Min so-far
\nclass Solution {\n    public int sumOfBeauties(int[] nums) {\n        int n = nums.length;\n        \n        // We can use a boolean array instead.\n        
```\nclass Solution {\n    public int sumOfBeauties(int[] nums) {\n        int n = nums.length;\n        \n        // We can use a boolean array instead.\n        int[] lr = new int[n];\n        int[] rl = new int[n];\n        int max = nums[0];\n        int min = nums[n-1];\n        \n        // If the i-th element is max so far, all the elements before it are smaller than i-th element.\n        for(int i = 1; i <= n - 2; ++i){\n            if(nums[i] > max) {\n                lr[i] = 1;\n                max = nums[i];\n            }\n        }\n        \n        // If the i-th element is min so far, all the elements after it are bigger than i-th element.\n        for(int i = n-2; i >= 1; --i){\n            if(nums[i] < min) {\n                rl[i] = 1;\n                min = nums[i];\n            }\n        }\n        // Stores the beauty count.\n        int b = 0;\n        for(int i = 1; i <= n-2; ++i) {\n            if(lr[i] == 1 && rl[i] == 1) b+=2;\n            else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) b+=1;\n        }\n        return b;\n    }\n}\n```
['Java']