Skip to content

Commit

Permalink
update 801 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Sep 9, 2024
1 parent 41255d3 commit b8d96e2
Showing 1 changed file with 37 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,43 @@

import java.util.Arrays;

/**
* 801. Minimum Swaps To Make Sequences Increasing
* Hard
* Topics
* Companies
* You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].
*
* For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
* Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.
*
* An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
*
*
*
* Example 1:
*
* Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
* Output: 1
* Explanation:
* Swap nums1[3] and nums2[3]. Then the sequences are:
* nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
* which are both strictly increasing.
* Example 2:
*
* Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
* Output: 1
*
*
* Constraints:
*
* 2 <= nums1.length <= 105
* nums2.length == nums1.length
* 0 <= nums1[i], nums2[i] <= 2 * 105
*
*
*/
// NOTE : An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
public class MinimumSwapsToMakeSequencesIncreasing {

// V0
Expand Down Expand Up @@ -104,12 +141,10 @@ public int solve(int nums1[], int nums2[], int ind, int[] dp) {
if (ind == nums1.length) return 0;

// Condition 1

if (ind > 0 && (nums1[ind - 1] >= nums1[ind] || nums2[ind - 1] >= nums2[ind])) {

// nums1[] = [3,2]
// nums2[] = [1,4]

int t = nums1[ind];
nums1[ind] = nums2[ind];
nums2[ind] = t;
Expand All @@ -120,7 +155,6 @@ public int solve(int nums1[], int nums2[], int ind, int[] dp) {
// nums1[] = [3,4]
// nums2[] = [1,2]
// therefore we have to swap it back so that we can have our original array.

t = nums1[ind];
nums1[ind] = nums2[ind];
nums2[ind] = t;
Expand All @@ -129,12 +163,10 @@ public int solve(int nums1[], int nums2[], int ind, int[] dp) {

}
// Condition 2

else if (ind > 0 && (nums1[ind - 1] >= nums2[ind] || nums2[ind - 1] >= nums1[ind])) {
return solve(nums1, nums2, ind + 1, dp);
}
// Condition 3

else {
if (dp[ind] != -1) return dp[ind];

Expand Down

0 comments on commit b8d96e2

Please sign in to comment.