|
| 1 | +/** |
| 2 | + * 2321. Maximum Score Of Spliced Array |
| 3 | + * https://leetcode.com/problems/maximum-score-of-spliced-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two 0-indexed integer arrays nums1 and nums2, both of length n. |
| 7 | + * |
| 8 | + * You can choose two integers left and right where 0 <= left <= right < n and swap the subarray |
| 9 | + * nums1[left...right] with the subarray nums2[left...right]. |
| 10 | + * - For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and |
| 11 | + * right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15]. |
| 12 | + * |
| 13 | + * You may choose to apply the mentioned operation once or not do anything. |
| 14 | + * |
| 15 | + * The score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum |
| 16 | + * of all the elements in the array arr. |
| 17 | + * |
| 18 | + * Return the maximum possible score. |
| 19 | + * |
| 20 | + * A subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the |
| 21 | + * subarray that contains the elements of nums between indices left and right (inclusive). |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} nums1 |
| 26 | + * @param {number[]} nums2 |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var maximumsSplicedArray = function(nums1, nums2) { |
| 30 | + const length = nums1.length; |
| 31 | + let sum1 = 0; |
| 32 | + let sum2 = 0; |
| 33 | + |
| 34 | + for (let i = 0; i < length; i++) { |
| 35 | + sum1 += nums1[i]; |
| 36 | + sum2 += nums2[i]; |
| 37 | + } |
| 38 | + |
| 39 | + let maxGain1 = 0; |
| 40 | + let maxGain2 = 0; |
| 41 | + let currGain1 = 0; |
| 42 | + let currGain2 = 0; |
| 43 | + |
| 44 | + for (let i = 0; i < length; i++) { |
| 45 | + currGain1 = Math.max(0, currGain1 + nums2[i] - nums1[i]); |
| 46 | + currGain2 = Math.max(0, currGain2 + nums1[i] - nums2[i]); |
| 47 | + maxGain1 = Math.max(maxGain1, currGain1); |
| 48 | + maxGain2 = Math.max(maxGain2, currGain2); |
| 49 | + } |
| 50 | + |
| 51 | + return Math.max(sum1 + maxGain1, sum2 + maxGain2); |
| 52 | +}; |
0 commit comments