Thursday, December 6, 2018

845. Longest Mountain in Array

Version #2 One pass without extra space
Using two counters to keep track of upCount and downCount
Reset them to zero if the mountain goes up after it goes down / two nodes are equal

97.72 %
class Solution {
    public int longestMountain(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int max = 0;
int upCount = 0;
int downCount = 0;
// 2,1,4,7,3,2,5
// A[i] -> upCount = 0, downCount = 0
for (int i = 1; i < A.length; i++) {
if (A[i] > A[i - 1]) {
if (downCount != 0) {
upCount = 0;
downCount = 0;
}
upCount++;
} else if (A[i] < A[i - 1]) {
downCount++;
} else { // A[i] == A[i - 1]
upCount = 0;
downCount = 0;
}
if (upCount > 0 && downCount > 0) {
max = Math.max(max, upCount + downCount + 1);
}
}
return max;
}
}

Version #1 Two pass with O(n) Space
Ref -> LC 821
14.84 %
class Solution {
    public int longestMountain(int[] A) {
// [[0,1,2,3,4,5,6,7,8,9]]
if (A == null || A.length == 0) {
return 0;
}
int len = A.length;
// length of up array until now, current node exclusive
int[] up = new int[len];
int upCount = 0;
for (int i = 0; i < len; i++) {
// 0 0 1 2 0 0 1
// 2 1 4 7 3 2 5
if (i != 0 && A[i] > A[i - 1]) {
up[i] = ++upCount;
} else {
upCount = 0;
up[i] = 0;
}
}
int downCount = 0;
int max = 0;
for (int i = len - 1; i >= 0; i--) {
if (i != len - 1 && A[i] > A[i + 1]) {
downCount++;
} else {
downCount = 0;
}
if (up[i] > 0 && downCount > 0) {
max = Math.max(max, downCount + up[i] + 1);
}
}
return max;
}
}

No comments:

Post a Comment