Skip to content

Added Longest Valid Parentheses Algorithm #529

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Dynamic-Programming/LongestValidParentheses.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
LeetCode -> https://leetcode.com/problems/longest-valid-parentheses/

Given a string containing just the characters '(' and ')',
find the length of the longest valid (well-formed) parentheses substring.
*/

const longestValidParentheses = (s) => {
const n = s.length
const stack = []

// storing results
const res = new Array(n).fill(-Infinity)

for (let i = 0; i < n; i++) {
const bracket = s[i]

if (bracket === ')' && s[stack[stack.length - 1]] === '(') {
res[i] = 1
res[stack[stack.length - 1]] = 1
stack.pop()
} else {
stack.push(i)
}
}

// summing all adjacent valid
for (let i = 1; i < n; i++) {
res[i] = Math.max(res[i], res[i] + res[i - 1])
}

// adding 0 if there are none so it will return 0 instead of -Infinity
res.push(0)
return Math.max(...res)
}

const main = () => {
console.log(longestValidParentheses(')()())')) // output -> 4
console.log(longestValidParentheses('')) // output -> 0
console.log(longestValidParentheses('(()')) // output -> 2
}

main()