Maximum Subarray / Best Time To Buy And Sell Stock 与 prefixNum
这两个系列的题目其实是同一套题,可以互相转换。
首先我们定义一个数组: prefixSum (前序和数组)
Given nums: [1, 2, -2, 3]
prefixSum: [0, 1, 3, 1, 4 ]
现在我们发现对prefixSum做Best Time To Buy And Sell Stock和对nums做Maximum Subarray,结果相同。
接下来我们就利用prefixSum解这两个系列的题目。
Question
Given an array of integers, find a contiguous subarray which has the largest sum.
Given the array [−2,2,−3,4,−1,2,1,−5,3]
, the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
The subarray should contain at least one number.
Solution
Sum of subarray i to j can be calculated by prefixSum[j] - prefixSum[i - 1].
Two variables, so we hope to make prefixSum[i - 1] minimum, while prefixSum[j] maximum.
Example
nums 1 1 1 -4 6 1 -5
prefixSum 0 1 2 3 -1 5 6 1
min 0 0 0 0 0 -1 -1 -1
max sub 0 1 2 3 3 6 7 7
public class Solution {
public int maxSubArray(ArrayList<Integer> nums) {
int length = nums.size();
// Construct prefixSum
int[] prefixSum = new int[length + 1];
prefixSum[0] = 0;
for (int i = 0; i < length; i++)
prefixSum[i + 1] = prefixSum[i] + nums.get(i);
// Traverse prefixSum
// min: minimum number before i
// result: maximum subarray from 0 to i
int min = 0;
int result = Integer.MIN_VALUE;
for (int i = 0; i < length; i++) {
int current = prefixSum[i + 1];
result = Math.max(result, current - min);
min = Math.min(current, min);
}
return result;
}
}
Similar: Minimum Subarray
public class Solution {
public int minSubArray(ArrayList<Integer> nums) {
int length = nums.size();
int sum = 0;
int maxSum = 0;
int minSum = Integer.MAX_VALUE;
for (int i = 0; i < length; i++) {
sum += nums.get(i);
minSum = Math.min((sum - maxSum), minSum);
maxSum = Math.max(maxSum, sum);
}
return minSum;
}
}
Question
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.
The subarray should contain at least one number
Solution
The problem can be translated as
Finding a strip line in the array, to make the sum of its max left subarray and max right subarray is max.
We can traverse the input array and list all possible value of the strip line, and then calculated its left max and right max. The time complexity is O(n2). But this still wastes a lot of time for duplicated calculation.
Actually we can just travers twice and get result. Time complexity is O(n).
maxLeft is max subarray on strip line's left side (inclusive). maxRight is max subarray on strip line's right side (inclusive).
nums 1 1 1 -4 6 1 -5
prefixSumLeft 0 1 2 3 -1 5 6 1
minL 0 0 0 0 0 -1 -1 -1
maxLeft 1 2 3 3 6 7 7
prefixSumRight 1 0 -1 -2 2 -4 -5 0
minR -5 -5 -5 -5 -5 -5 0 0
maxRight 7 7 7 7 7 1 0
public class Solution { public int maxTwoSubArrays(ArrayList<Integer> nums) {
int length = nums.size();
int[] left = new int[length];
int[] right = new int[length];
int sum = 0;
int minSum = 0;
int maxSum = Integer.MIN_VALUE;
// left
for (int i = 0; i < length; i++) {
sum += nums.get(i);
maxSum = Math.max(maxSum, (sum - minSum));
left[i] = maxSum;
minSum = Math.min(minSum, sum);
}
// right
sum = 0;
minSum = 0;
maxSum = Integer.MIN_VALUE;
for (int i = length - 1; i >= 0; i--) {
sum += nums.get(i);
maxSum = Math.max(maxSum, (sum - minSum));
right[i] = maxSum;
minSum = Math.min(minSum, sum);
} int result = Integer.MIN_VALUE;
for (int i = 0; i < length - 1; i++)
result = Math.max(result, left[i] + right[i + 1]);
return result;
}
}
Question
Given an array of integers and a number k, find k non-overlapping
subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
Given [-1,4,-2,3,-2,3]
, k=2
, return 8
The subarray should contain at least one number
Solution
Maximum Subarray / Best Time To Buy And Sell Stock 与 prefixNum的更多相关文章
- Week 7 - 714. Best Time to Buy and Sell Stock with Transaction Fee & 718. Maximum Length of Repeated Subarray
714. Best Time to Buy and Sell Stock with Transaction Fee - Medium Your are given an array of intege ...
- LeetCode--Best Time to Buy and Sell Stock (贪心策略 or 动态规划)
Best Time to Buy and Sell Stock Total Accepted: 14044 Total Submissions: 45572My Submissions Say you ...
- 121. Best Time to Buy and Sell Stock【easy】
121. Best Time to Buy and Sell Stock[easy] Say you have an array for which the ith element is the pr ...
- [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] Best Time to Buy and Sell Stock III 买股票的最佳时间之三
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] Best Time to Buy and Sell Stock II 买股票的最佳时间之二
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- [LeetCode] Best Time to Buy and Sell Stock 买卖股票的最佳时间
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- [LintCode] Best Time to Buy and Sell Stock II 买股票的最佳时间之二
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
随机推荐
- c语言局部变量 静态局部变量 全局变量与静态全局变量
基本概念: 作用域:起作用的区域,也就是可以工作的范围. 代码块:所谓代码块,就是用{}括起来的一段代码. 数据段:数据段存的是数,像全局变量就是存在数据段的 代码段:存的是程序代码,一般是只读的. ...
- [转载]Linux的时间与时钟中断处理
本文主要介绍在Linux下的时间实现以及系统如何进行时钟中断处理. 一. Linux的硬件时间 PC机中的时间有三种硬件时钟实现,这三种都是基于晶振产生的方波信号输入.这三种时钟为: 实时时钟RTC ...
- Redhat6.4 配置本地网络的FTP YUM源
Redhat6.4 配置本地网络的FTP YUM源 如果本机IP: 192.168.8.47 (一) 配置本机的yum源 使用以下的方法能够配置本机的yum源: 1) scp命令上传ISO文件到: / ...
- ORACLE查看数据文件-控制文件-日志文件-表空间信息
1.查看当前数据库中的所有用户:select username from dba_users; 2.查看当前会话登录的用户:show user或select username from user_us ...
- String功能测试
package foxe; import java.io.IOException;import java.util.StringTokenizer; public class MainClass { ...
- oracle 存储过程返回结果集 (转载)
好久没上来了, 难道今天工作时间稍有空闲, 研究了一下oracle存储过程返回结果集. 配合oracle临时表, 使用存储过程来返回结果集的数据读取方式可以解决海量数据表与其他表的连接问题. 在存储过 ...
- DataTable转json字符串,jQuery.parseJSON()把json字符串转为标准的json对象格式
1.string res = DataTableToJson.DataTable2Json(dt);讲DataTable转换为json字符串 http://www.365mini.com/page/j ...
- 深入javascript——构造函数和原型对象
常用的几种对象创建模式 使用new关键字创建 最基础的对象创建方式,无非就是和其他多数语言一样说的一样:没对象,你new一个呀! var gf = new Object(); gf.name = &q ...
- Linux下使用多线程模拟异步网络通信
服务器 /* socket server * 2014-12-15 CopyRight (c) arbboter */ #include <unistd.h> #include <s ...
- 我和小美的撸码日记(1)之软件也需靠脸吃饭,带您做张明星脸(附后台经典框架 DEMO 下载)
众所周知程序员得靠技术吃饭,但是真的光靠技术就够了吗?Teacher苍,一位德艺双馨的艺术家,论技术她自然是炉火纯青,我觉得她桃李遍天下的原因不仅限于些,试想如果Teacher苍长得跟凤姐一样再带点乡 ...