|
| 1 | +# Mountain Split Pattern | 42 Lines | O(n) | 6ms |
| 2 | + |
| 3 | +# Intuition |
| 4 | +We need to find a split point where the left part is strictly increasing and the right part is strictly decreasing. The array must follow a "mountain" pattern - it can only increase then decrease, never increase again after decreasing. |
| 5 | + |
| 6 | +# Approach |
| 7 | +Traverse the array once to identify the pattern. Track when we transition from increasing to decreasing (the peak). If the array increases again after decreasing, return -1. Handle three cases: purely increasing arrays, fixed peak positions, and moveable peaks where we can assign the peak element to either side for optimal difference. |
| 8 | + |
| 9 | +# Complexity |
| 10 | +- Time complexity: $$O(n)$$ |
| 11 | +- Space complexity: $$O(1)$$ |
| 12 | + |
| 13 | +# Code |
| 14 | +```typescript |
| 15 | +const splitArray = (nums: number[]): number => { |
| 16 | + if (nums.length === 2) return Math.abs(nums[0] - nums[1]); |
| 17 | + |
| 18 | + let isStillIncreasing = true; |
| 19 | + let leftSum = nums[0]; |
| 20 | + let rightSum = 0; |
| 21 | + let peakIndex = 0; |
| 22 | + |
| 23 | + for (let currentIndex = 1; currentIndex < nums.length; currentIndex++) { |
| 24 | + const currentElement = nums[currentIndex]; |
| 25 | + const previousElement = nums[currentIndex - 1]; |
| 26 | + |
| 27 | + if (isStillIncreasing && currentElement <= previousElement) { |
| 28 | + isStillIncreasing = false; |
| 29 | + peakIndex = currentIndex - 1; |
| 30 | + } else if (!isStillIncreasing && currentElement >= previousElement) { |
| 31 | + return -1; |
| 32 | + } |
| 33 | + |
| 34 | + if (isStillIncreasing) { |
| 35 | + leftSum += currentElement; |
| 36 | + } else { |
| 37 | + rightSum += currentElement; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + if (isStillIncreasing) { |
| 42 | + const lastElement = nums[nums.length - 1]; |
| 43 | + return Math.abs(leftSum - lastElement * 2); |
| 44 | + } |
| 45 | + |
| 46 | + const peakElement = nums[peakIndex]; |
| 47 | + const nextElement = nums[peakIndex + 1]; |
| 48 | + if (peakIndex === 0 || peakElement <= nextElement) { |
| 49 | + return Math.abs(leftSum - rightSum); |
| 50 | + } |
| 51 | + |
| 52 | + const sumWithPeakInLeft = Math.abs(leftSum - rightSum); |
| 53 | + const sumWithPeakInRight = Math.abs((leftSum - peakElement) - (rightSum + peakElement)); |
| 54 | + |
| 55 | + return Math.min(sumWithPeakInLeft, sumWithPeakInRight); |
| 56 | +}; |
| 57 | +``` |
0 commit comments