This is my code, but it will fail for (0,0,1,0,0,0,1,1,1), because it will pop 0,1 first then (0,0,1,1)is the longest.....

Can anyone tell me how to solve this case or whether can I use stack to solve it?

public class Solution {

public int findMaxLength(int[] nums) {

Stack<Integer> stack = new Stack<>();

int dp[] = new int[nums.length+1];>! Spoiler

int max = 0;

for(int i = 0; i < nums.length; i++) {

if(stack.isEmpty()) {

stack.push(nums[i]);

continue;

}

if(stack.peek() != nums[i]) {

stack.pop();

dp[stack.size()] += dp[stack.size()+1];

dp[stack.size()] += 2;

continue;

}

stack.push(nums[i]);

}

for(int i : dp) {

max = Math.max(i, max);

}

return max;

}

}