Explanation:
The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Input:
nums = [1,1,0,1,1,1]
Output:
3
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
import java.io.*;
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int res = 0;
int count = 0;
for(int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
if (res < count)
res = count;
} else
count = 0;
}
return res;
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int[] nums = new int[input.length];
for (int i = 0; i < input.length; i++) {
nums[i] = Integer.parseInt(input[i].trim());
}
Solution solution = new Solution();
int res = solution.findMaxConsecutiveOnes(nums);
System.out.println(res);
}
}
그냥 1이 들어올 때 count를 해주고, 만약 그 카운트가 내가 저장하고 있던 최고 높은 count보다 크면 count를 갈아치우는 형식으로 간단하게 짰다. leetcode는 형식이 class 형식으로 예제가 나와있었다. 그래서 맞춰서 쓰려면 매소드를 써야 했는데 자바를 문제 풀면서 배우다보니 개념이 엉망이라 좀 힘들었다. 이제 자바를 좀 체계적으로 공부해야겠다는 생각이 든다.
'알고리즘' 카테고리의 다른 글
가장 많이 받은 선물 (0) | 2024.07.10 |
---|---|
이웃한 칸 (1) | 2024.05.29 |
[python] 1267번 휴대폰 요금 (0) | 2023.09.21 |
[python] 1085번: 직사각형에서 탈출 (0) | 2023.09.20 |
[python] 2525번: 오븐 시계 (2) | 2023.09.09 |