中级农民
- 积分
- 274
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-7-16
- 最后登录
- 1970-1-1
|
翻到自己这页,给大家发个我当时写的完整版吧 233
import java.util.*;
public class eBayIllustration{
public static void main(String[] args) {
int[] input = new int[]{10, 30, -40, 3};
eBayIllustration sol = new eBayIllustration();
int[] res = sol.maxSubarrayAtMostK(input, 2);
if (res == null) {
System.out.println("no one was selected");
} else {
System.out.println(res[0] + "~" + res[1]);
}
}
// basically, my idea is maintain a deque to contains currently valid min value
// valid means the min value must be in the scope of k from current i
// Time: O(N)
// Space: O(N)
public int[] maxSubarrayAtMostK(int[] input, int k) {
if (input == null || input.length == 0) {
return new int[0];
}
// Preprocessing
// nums[i] represents the sum : input[0] + ... input[i - 1]
int[] nums = new int[input.length + 1];
for (int i = 1; i < nums.length; i++) {
nums[i] = nums[i - 1] + input[i - 1];
}
Deque<Integer> deque = new LinkedList<>();
int max = 0;
int[] candidate = null;
for (int i = 0; i < nums.length; i++) {
while (!deque.isEmpty() && nums[deque.peekLast()] >= nums[i]) {
deque.pollLast();
}
deque.addLast(i);
// out of scope
if (deque.peekFirst() < i - k) {
deque.pollFirst();
}
// if better subarray appear, update the result/candidate
if (nums[i] - nums[deque.peekFirst()] > max) {
max = nums[i] - nums[deque.peekFirst()];
candidate = new int[]{deque.peekFirst(), i - 1}; //inclusive idx
}
}
return candidate;// e.g [1,3] 1 means the left bound 3 means the right bound of the subarray of input, bothe left and right bound are inclusive.
}
} |
|