티스토리 뷰

Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

 

Example 1:

Input: s = "011101" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right = "1101", score = 1 + 3 = 4 left = "011" and right = "101", score = 1 + 2 = 3 left = "0111" and right = "01", score = 1 + 1 = 2 left = "01110" and right = "1", score = 2 + 1 = 3

Example 2:

Input: s = "00111" Output: 5 Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5

Example 3:

Input: s = "1111" Output: 3

 

Constraints:

  • 2 <= s.length <= 500
  • The string s consists of characters '0' and '1' only.

문제를 간단히 설명하면

 

1. 011101이라는 문자열이 있을때 이 문자열을 왼쪽, 오른쪽 두 부분으로 나눈다

2. 그럼 ([0], [11101]), ([01], [1101]) ... 과 같은 케이스 들이 나온다.

3. 왼쪽 파트에서 0의 개수와 오른쪽 파트에서의 1의 개수를 합했을때 최대값을 갱신하면 된다.

 

이 문제를 왼쪽 포인터를 위한 루프1개 , 오른쪽 포인터를 위한 루프1개, 그리고 각 포인터를 이동시켜주기 위해 루프 1개 총3개의 루프인 3중 for문으로도 문제를 풀 수 있지만 비효율적이다.

 

그래서 나는 한번 배열을 쭉 스캔해서 현재 인덱스까지의 0의 개수와 1의 개수를 각각 다른 배열에 집어 넣어놨다.

그리고 나서 한번더 0의 개수와 1의 개수가 기록된 배열을 체크하면서 최대값을 갱신했다.

/**
 * @param {string} s
 * @return {number}
 */
var maxScore = function(s) {
    const arr1 = [];
    const arr2 = [];
    let zero = 0;
    let one = 0;
    
    for(let i=0; i<s.length; i++) {
        const left = i;
        const right = s.length - i - 1;
        arr1[left] = s[left] === '0' ? ++zero : zero;
        arr2[right] = s[right] === '1' ? ++one : one;
    }
    
    let answer = 0;
    for(let i=0; i<s.length - 1; i++) {
        answer = Math.max(answer, arr1[i] + arr2[i+1]);
    }
    return answer;
};

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함