Skip to content

Commit f2b7178

Browse files
committed
Add solution #801
1 parent 13a615e commit f2b7178

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,7 @@
610610
797|[All Paths From Source to Target](./0797-all-paths-from-source-to-target.js)|Medium|
611611
798|[Smallest Rotation with Highest Score](./0798-smallest-rotation-with-highest-score.js)|Hard|
612612
799|[Champagne Tower](./0799-champagne-tower.js)|Medium|
613+
801|[Minimum Swaps To Make Sequences Increasing](./0801-minimum-swaps-to-make-sequences-increasing.js)|Hard|
613614
802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium|
614615
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|
615616
819|[Most Common Word](./0819-most-common-word.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 801. Minimum Swaps To Make Sequences Increasing
3+
* https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/
4+
* Difficulty: Hard
5+
*
6+
* You are given two integer arrays of the same length nums1 and nums2. In one operation, you are
7+
* allowed to swap nums1[i] with nums2[i].
8+
*
9+
* For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to
10+
* obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
11+
*
12+
* Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The
13+
* test cases are generated so that the given input always makes it possible.
14+
*
15+
* An array arr is strictly increasing if and only if
16+
* arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
17+
*/
18+
19+
/**
20+
* @param {number[]} nums1
21+
* @param {number[]} nums2
22+
* @return {number}
23+
*/
24+
var minSwap = function(nums1, nums2) {
25+
let noSwap = 0;
26+
let swap = 1;
27+
28+
for (let i = 1; i < nums1.length; i++) {
29+
let nextNoSwap = Infinity;
30+
let nextSwap = Infinity;
31+
32+
const canKeepBoth = nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1];
33+
const canSwapBoth = nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1];
34+
35+
if (canKeepBoth) {
36+
nextNoSwap = Math.min(nextNoSwap, noSwap);
37+
nextSwap = Math.min(nextSwap, swap + 1);
38+
}
39+
40+
if (canSwapBoth) {
41+
nextNoSwap = Math.min(nextNoSwap, swap);
42+
nextSwap = Math.min(nextSwap, noSwap + 1);
43+
}
44+
45+
noSwap = nextNoSwap;
46+
swap = nextSwap;
47+
}
48+
49+
return Math.min(noSwap, swap);
50+
};

0 commit comments

Comments
 (0)