Notice
250x250
Recent Posts
Recent Comments
Link
넘치게 채우기
[LeetCode] 1574. Shortest Subarray to be Removed to Make Array Sorted 본문
PS/LeetCode
[LeetCode] 1574. Shortest Subarray to be Removed to Make Array Sorted
riveroverflow 2024. 11. 15. 21:39728x90
반응형
leetcode - Shortest Subarray to be Removed to Make Array Sorted
문제 유형: 그리디, 투 포인터
문제 난이도: Medium
문제
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
Return the length of the shortest subarray to remove.
A subarray is a contiguous subsequence of the array.
정수 배열 arr이 주어집니다.
비내림차순 배열이 되도록 요소를 없앨 수 있는데, 최소개수로 없애는 수를 구하시오.
풀이
비내림차순 배열을 만들기 위해, 양쪽의 최선의 비내림차순 부분배열을 만들어본다.
왜냐하면 맨 왼쪽에는 작은 수들이, 맨 오른쪽에는 큰 수들이 와야 하기 떄문이다.
그렇게 두 부분배열을 구해서, 병합한다.
전체 길이에서 그 병합된 부분의 길이가 빠진게 정답이다.
코드
C++
class Solution {
public:
int findLengthOfShortestSubarray(vector<int>& arr) {
int n = arr.size();
int left = 0;
int right = n-1;
while(left < n-1 && arr[left+1] >= arr[left]) left++;
if(left == n-1) return 0;
while(right > 0 && arr[right-1] <= arr[right]) right--;
int ans = min(n - left - 1, right);
int i = 0, j = right;
while(i <= left && j < n) {
if(arr[i] <= arr[j]) {
ans = min(ans, j-i-1);
i++;
} else {
j++;
}
}
return ans;
}
};
728x90
반응형
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 862. Shortest Subarray with Sum at Least K (0) | 2024.11.17 |
---|---|
[LeetCode] 3254. Find the Power of K-Size Subarrays I (0) | 2024.11.16 |
[LeetCode] 2064. Minimized Maximum of Products Distributed to Any Store (0) | 2024.11.14 |
[LeetCode] 2563. Count the Number of Fair Pairs (0) | 2024.11.13 |
[LeetCode] 2070. Most Beautiful Item for Each Query (0) | 2024.11.12 |