-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path915-PartitionArrayIntoDisjointIntervals.go
More file actions
72 lines (61 loc) · 1.94 KB
/
915-PartitionArrayIntoDisjointIntervals.go
File metadata and controls
72 lines (61 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
// 915. Partition Array into Disjoint Intervals
// Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:
// Every element in left is less than or equal to every element in right.
// left and right are non-empty.
// left has the smallest possible size.
// Return the length of left after such a partitioning.
// Test cases are generated such that partitioning exists.
// Example 1:
// Input: nums = [5,0,3,8,6]
// Output: 3
// Explanation: left = [5,0,3], right = [8,6]
// Example 2:
// Input: nums = [1,1,1,0,6,12]
// Output: 4
// Explanation: left = [1,1,1,0], right = [6,12]
// Constraints:
// 2 <= nums.length <= 10^5
// 0 <= nums[i] <= 10^6
// There is at least one valid answer for the given input.
import "fmt"
func partitionDisjoint(nums []int) int {
localmx, mx, index := nums[0], nums[0], 0
for i := range nums {
if localmx > nums[i] {
localmx = mx
index = i
} else {
if nums[i] > mx {
mx = nums[i]
}
}
}
return index + 1
}
func partitionDisjoint1(nums []int) int {
leftMax, curMax, index := nums[0], nums[0], 0
max := func (x, y int) int { if x > y { return x; }; return y; }
for i := 1; i < len(nums) - 1; i++ {
curMax = max(curMax, nums[i])
if nums[i] < leftMax {
leftMax = curMax
index = i
}
}
return index + 1
}
func main() {
// Example 1:
// Input: nums = [5,0,3,8,6]
// Output: 3
// Explanation: left = [5,0,3], right = [8,6]
fmt.Println(partitionDisjoint([]int{5,0,3,8,6})) // 3
// Example 2:
// Input: nums = [1,1,1,0,6,12]
// Output: 4
// Explanation: left = [1,1,1,0], right = [6,12]
fmt.Println(partitionDisjoint([]int{1,1,1,0,6,12})) // 4
fmt.Println(partitionDisjoint1([]int{5,0,3,8,6})) // 3
fmt.Println(partitionDisjoint1([]int{1,1,1,0,6,12})) // 4
}