Given an array of integers called nums, you can perform the following operation while nums contains at least 2 elements:
- Choose the first two elements of nums and delete them.
The score of the operation is the sum of the deleted elements.
Your task is to find the maximum number of operations that can be performed, such that all operations have the same score.
Return the maximum number of operations possible that satisfy the condition mentioned above.
Example 1:
Input: nums = [3,2,1,4,5]
Output: 2
Explanation: We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [1,4,5].
- Delete the first two elements, with score 1 + 4 = 5, nums = [5].
We are unable to perform any more operations as nums contain only 1 element.
Example 2:
Input: nums = [3,2,6,1,4]
Output: 1
Explanation: We perform the following operations:
- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].
We are unable to perform any more operations as the score of the next operation isn't the same as the previous one.
출처 : https://leetcode.com/problems/maximum-number-of-operations-with-the-same-score-i/description/
풀이
function maxOperations(nums: number[]): number {
if(nums.length<2)return 0;
var k = nums[0]+nums[1];
var cnt =1;
for(var i=2 ; i+1<nums.length ; i+=2){
if((nums[i]+nums[i+1]) == k)cnt++;
else break;
}
return cnt;
};
주어진 숫자 배열 nums에서 특정한 규칙에 따라 쌍(pair)을 찾아내는 작업
- 인덱스 i를 2로 시작해서 배열의 끝까지 반복합니다. 단, 두 요소씩 건너뛰며 반복(i += 2).
- 반복문 내에서 현재 요소(nums[i])와 다음 요소(nums[i+1])의 합이 k와 같은지 검사
- 같다면 cnt를 1 증가
- 같지 않으면 반복문을 중단
- 최종적으로 카운터 cnt를 반환.
즉, 이 함수는 배열에서 처음 두 요소의 합과 동일한 합을 가지는 연속적인 쌍의 최대 개수를 계산
예시:
- 입력: [1, 2, 3, 4, 5, 6, 7, 8]
- 첫 번째 두 요소의 합: 1 + 2 = 3
- 그 다음 두 요소의 합: 3 + 4 = 7 (다르기 때문에 여기서 중단)
- 결과: cnt = 1
'LeetCode' 카테고리의 다른 글
| 2293. Min Max Game / TypeScript (0) | 2024.05.29 |
|---|---|
| 938. Range Sum of BST / TypeScript (0) | 2024.05.28 |
| 1974. Minimum Time to Type Word Using Special Typewriter (0) | 2024.05.25 |
| 563. Binary Tree Tilt (0) | 2024.05.24 |
| 1640. Check Array Formation Through Concatenation / TypeScript (0) | 2024.05.21 |