세 가지 동작의 최대값과 최소값 간의 최소 차이

WBOY
풀어 주다: 2024-07-18 22:44:21
원래의
1037명이 탐색했습니다.

Minimum Difference Between Largest and Smallest Value in Three Moves

1509. 세 가지 동작에서 최대값과 최소값의 최소 차이

중간

정수 배열 nums가 주어졌습니다.

한 번에 숫자 요소 하나를 선택하고어떤 값으로든 변경할 수 있습니다.

최대 3번의 동작을 수행한 후nums의 최대값과 최소값 사이의 최소 차이를 반환합니다.

예 1:

  • 입력:숫자 = [5,3,2,4]
  • 출력:0
  • 설명:최대 3개의 동작을 만들 수 있습니다.
In the first move, change 2 to 3. nums becomes [5,3,3,4]. In the second move, change 4 to 3. nums becomes [5,3,3,3]. In the third move, change 5 to 3. nums becomes [3,3,3,3]. After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
로그인 후 복사

예 2:

  • 입력:숫자 = [1,5,0,10,14]
  • 출력:1
  • 설명:최대 3개의 동작을 만들 수 있습니다.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14]. In the second move, change 10 to 0. nums becomes [1,0,0,0,14]. In the third move, change 14 to 1. nums becomes [1,0,0,0,1]. After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1. It can be shown that there is no way to make the difference 0 in 3 moves.
로그인 후 복사

예 3:

  • 입력:숫자 = [3,100,20]
  • 출력:0
  • 설명:최대 3개의 동작을 만들 수 있습니다.
In the first move, change 100 to 7. nums becomes [3,7,20]. In the second move, change 20 to 7. nums becomes [3,7,7]. In the third move, change 3 to 7. nums becomes [7,7,7]. After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
로그인 후 복사

제약조건:

  • 1 <= nums.length <= 105
  • -109<= 숫자[i] <= 109

해결책:

class Solution { /** * @param Integer[] $nums * @return Integer */ function minDifference($nums) { $n = count($nums); // If the array has 4 or fewer elements, the difference is zero because we can remove all but one element. if ($n <= 4) { return 0; } // Sort the array to facilitate the calculation of differences after removals. sort($nums); // We consider removing 0, 1, 2, or 3 elements from the start or the end. // Calculate the differences: // 1. Remove 3 from start: nums[n-1] - nums[3] // 2. Remove 2 from start, 1 from end: nums[n-2] - nums[2] // 3. Remove 1 from start, 2 from end: nums[n-3] - nums[1] // 4. Remove 3 from end: nums[n-4] - nums[0] $differences = [ $nums[$n - 1] - $nums[3], $nums[$n - 2] - $nums[2], $nums[$n - 3] - $nums[1], $nums[$n - 4] - $nums[0] ]; // Return the minimum difference. return min($differences); } }
로그인 후 복사

연락처 링크

  • 링크드인
  • 깃허브

위 내용은 세 가지 동작의 최대값과 최소값 간의 최소 차이의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!