반응형
https://leetcode.com/problems/max-consecutive-ones/description/
Max Consecutive Ones - LeetCode
Can you solve this real interview question? Max Consecutive Ones - Given a binary array nums, return the maximum number of consecutive 1's in the array. Example 1: Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 ans 구간 별 최대 길이를 저장할 변수 cnt를 선언 후 0으로 각각 초기화 해 줍니다.
📔 풀이과정
1. num의 원소를 순회합니다.2. 중간에 0이거나 vector의 끝이라면 ans를 cnt와 비교해 max값으로 갱신해줍니다.
📔 정답 출력 | 반환
ans를 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ans = 0;
int cnt = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i]) cnt++;
if(!nums[i] || i == nums.size() - 1) {
ans = max(ans, cnt);
cnt = 0;
}
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 495. Teemo Attacking.cpp (0) | 2023.03.31 |
---|---|
(C++) - LeetCode (easy) 492. Construct the Rectangle (0) | 2023.03.29 |
(C++) - LeetCode (easy) 461. Hamming Distance (0) | 2023.03.23 |
(C++) - LeetCode (easy) 441. Arranging Coins (0) | 2023.03.15 |
(Python) - LeetCode (easy) 415. Add Strings (0) | 2023.03.13 |