Maximum Sum Circular Subarray LT918
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)
Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)
Example 1:
Input: [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3
Example 2:
Input: [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10
Example 3:
Input: [3,-1,2,-1]
Output: 4
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4
Example 4:
Input: [3,-2,2,-3]
Output: 3
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
Example 5:
Input: [-2,-3,-1]
Output: -1
Explanation: Subarray [-1] has maximum sum -1
Idea 1. Similar to Maximum Subarray LT53, the difference is the circular array part, the subarray could be the tail(A[j..n-1]) plus the head(A[0..i]) (i+1 < j), if the subarray of tail + head is the maximum, the subarray in the middle is A[i+1, j-1] has the minSum, once the minSum is found, the maxSum is Sum - minSum, except maxSum = 0 if all values in the array are negative, as minSum == Sum.
Note. negative arrays
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public int maxSubarraySumCircular(int[] A) {
int maxSoFar = 0;
int minSoFar = 0;
int sum = 0;
int minSum = Integer.MAX_VALUE;
int maxSum = Integer.MIN_VALUE;
for(int a: A) {
maxSoFar = a + Math.max(maxSoFar, 0);
maxSum = Math.max(maxSum, maxSoFar);
minSoFar = a + Math.min(minSoFar, 0);
minSum = Math.min(minSum, minSoFar);
sum += a;
}
if(sum == minSum) {
return maxSum;
}
return Math.max(maxSum, sum - minSum);
}
}
Idea 2. 另外一种方法求2个intervals (head + tail)组成的,如果直接从左到右+从右到左的和,可能中间有重合,固定一边,求另外一边的和的最大值,保证j >= i+2.
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public int maxSubarraySumCircular(int[] A) {
int curr = 0;
int n = A.length;
int maxSum = Integer.MIN_VALUE;
for(int a: A) {
curr = a + Math.max(curr, 0);
maxSum = Math.max(maxSum, curr);
}
int[] rightMaxSum = new int[n];
rightMaxSum[n-1] = A[n-1];
curr = A[n-1];
for(int i = n-2; i >= 0; --i) {
curr += A[i];
rightMaxSum[i] = Math.max(curr, rightMaxSum[i+1]);
}
curr = 0;
int result = maxSum;
for(int i = 0; i+2 < n; ++i) {
curr += A[i];
result = Math.max(result, curr + rightMaxSum[i+2]);
}
return result;
}
}
Idea 3. Similar to sliding window minValue, build a min deque for prefix sum, for each prefix sum, find the minimum of previous prefixSum so that the subarray sum ending here is the maximu, since it's circular array, j - i <= n, remove the invalid previous index. Note: store the index
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public int maxSubarraySumCircular(int[] A) {
Deque<Integer> minPrefix = new LinkedList<>();
minPrefix.addLast(0);
int n = A.length;
int[] prefix = new int[2*n + 1];
for(int i = 0; i < 2*n; ++i) {
prefix[i+1] = prefix[i] + A[i%n];
}
int result = Integer.MIN_VALUE;
for(int i = 1; i <= 2*n; ++i) {
if(i - minPrefix.getFirst() > n) {
minPrefix.removeFirst();
}
result = Math.max(result, prefix[i] - prefix[minPrefix.getFirst()]);
while(!minPrefix.isEmpty() && prefix[minPrefix.getLast()] >prefix[i]) {
minPrefix.removeLast();
}
minPrefix.add(i);
}
return result;
}
}
Note:
-30000 <= A[i] <= 300001 <= A.length <= 30000
Maximum Sum Circular Subarray LT918的更多相关文章
- LC 918. Maximum Sum Circular Subarray
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- [Swift]LeetCode918. 环形子数组的最大和 | Maximum Sum Circular Subarray
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- 918. Maximum Sum Circular Subarray
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- [LeetCode] 918. Maximum Sum Circular Subarray 环形子数组的最大和
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- Leetcode Week5 Maximum Sum Circular Subarray
Question Given a circular array C of integers represented by A, find the maximum possible sum of a n ...
- 动态规划-Maximum Subarray-Maximum Sum Circular Subarray
2020-02-18 20:57:58 一.Maximum Subarray 经典的动态规划问题. 问题描述: 问题求解: public int maxSubArray(int[] nums) { i ...
- [LeetCode] Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
- [Swift]LeetCode689. 三个无重叠子数组的最大和 | Maximum Sum of 3 Non-Overlapping Subarrays
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
- [leetcode]689. Maximum Sum of 3 Non-Overlapping Subarrays三个非重叠子数组的最大和
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
随机推荐
- HTML5 full-screen全屏API
这篇文章纯属记录,非常感谢张鑫旭大神的demo 原文地址: http://www.zhangxinxu.com/study/201210/html5-full-screen-api.html 代码 C ...
- 关于单元测试时加载spring-context.xml文件的问题
在进行web开发的时候,通常我们都会使用Spring框架,使用spring容器管理java bean. 而spring的配置文件有时候放在classpath下面,有时候放在WEB-INF下面. 一般在 ...
- python3下同时取得exe、zip和chm下载地址
from selenium import webdriverimport osimport timeimport re cur_path=os.getcwd() #得到程序的当前目录str_file= ...
- java面试题复习(一)
//基础最重要,如果面试官问一个答不上一个,那有难度的都都不用问了,直接就pass了,就像我,嘿嘿. //每天最好熟记10个问题,这些问题在编程是会很厚帮助,帮你避免很多不应该出现的错误. 一.面向对 ...
- C# 构造函数中base和this的使用。
使用base时,首先给父类中的构造函数赋值. 使用this时,先调用父类无参构造函数,再调用自身其他构造函数并对其赋值,最后调用自身当前构造函数.
- Git综合使用命令行和gui工具小结
使用Git的时候,综合使用命令行和gui工具,可以把Git用的最舒服,因此这里总结下使用gui和命令行的一些对应操作, gui中拉取:git pull origin dev_branch gui中推送 ...
- [Design] 后端程序的高并发与异步
既然涉及到高并发这个概念,就少不了先谈这么几个概念,并发数.多进程.多线程.协程.负载均衡. 操作系统上讲的并发是操作系统上有几个程序在同时执行,单核CPU在微观上是由CPU调度执行,非同时执行,多核 ...
- shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
let a = [1, 2, 3]; let b = a.shift(); console.log(a); // [2, 3] console.log(b); // 1 返回值 从数组中删除的元素; ...
- Loadrunner回放https脚本时出现错误Error -27780 Connection reset by peer解决办法
录制好的https协议的web脚本,在脚本回放时会出现Error -27780: [GENERAL_MSG_CAT_SSL_ERROR]connect to host "......&quo ...
- lanya
var app = getApp() Page({ data: { motto: 'Hello World', openBLE:'打开蓝牙设备', startBLEDiscover ...