-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumOfSubarrrayRanges.java
More file actions
74 lines (61 loc) · 2.05 KB
/
SumOfSubarrrayRanges.java
File metadata and controls
74 lines (61 loc) · 2.05 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
73
74
package stack;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/sum-of-subarray-ranges
* Difficulty: Medium
*/
public class SumOfSubarrrayRanges {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public long subArrayRangesViaMonotonicStack(int[] nums) {
return sumOfMaxs(nums) - sumOfMins(nums);
}
private long sumOfMins(int[] nums) {
Deque<Integer> stack = new LinkedList<>();
long sum = 0L;
for (int right = 0; right <= nums.length; right++) {
while (!stack.isEmpty() && (right == nums.length || nums[stack.peek()] >= nums[right])) {
int min = stack.pop();
int left = !stack.isEmpty() ? stack.peek() : -1;
long count = (long) (right - min) * (min - left);
sum += count * nums[min];
}
stack.push(right);
}
return sum;
}
private long sumOfMaxs(int[] nums) {
Deque<Integer> stack = new LinkedList<>();
long sum = 0L;
for (int right = 0; right <= nums.length; right++) {
while (!stack.isEmpty() && (right == nums.length || nums[stack.peek()] <= nums[right])) {
int min = stack.pop();
int left = !stack.isEmpty() ? stack.peek() : -1;
long count = (long) (right - min) * (min - left);
sum += count * nums[min];
}
stack.push(right);
}
return sum;
}
/**
* Time complexity: O(n^2)
* Space complexity: O(1)
*/
public long subArrayRangesViaBruteForce(int[] nums) {
long sum = 0L;
for (int start = 0; start < nums.length; start++) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int end = start; end < nums.length; end++) {
min = Math.min(min, nums[end]);
max = Math.max(max, nums[end]);
sum += max - min;
}
}
return sum;
}
}