这两个系列的题目其实是同一套题,可以互相转换。

首先我们定义一个数组: 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解这两个系列的题目。

Maximum Subarray

Question

Given an array of integers, find a contiguous subarray which has the largest sum.

Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Note

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;
}
}

Maximum Subarray II

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.

Example

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.

Note

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;
}
}

Maximum Subarray III

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.

Example

Given [-1,4,-2,3,-2,3]k=2, return 8

Note

The subarray should contain at least one number

Solution

   

Maximum Subarray / Best Time To Buy And Sell Stock 与 prefixNum的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 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 ...

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. BaseAdapter自定义适配器——思路详解

    BaseAdapter自定义适配器——思路详解 引言: Adapter用来把数据绑定到扩展了AdapterView类的视图组.系统自带了几个原生的Adapter. 由于原生的Adapter视图功能太少 ...

  2. hdu2089:不要62(基础数位dp)

    题意:规定一个合法的号码不能含有4或者是连续的62 给定区间[n,m] 问此区间内合法的号码的个数 分析:数位dp dp[i][j]代表 最高位为 j 的 i 位数有多少个合法的 然后按题目规则进行转 ...

  3. Java高级软件工程师面试考纲

    如果要应聘高级开发工程师职务,仅仅懂得Java的基础知识是远远不够的,还必须懂得常用数据结构.算法.网络.操作系统等知识.因此本文不会讲解具体的技术,笔者综合自己应聘各大公司的经历,整理了一份大公司对 ...

  4. java_final

  5. Android应用开发提高系列(4)——Android动态加载(上)——加载未安装APK中的类

    前言 近期做换肤功能,由于换肤程度较高,受限于平台本身,实现起来较复杂,暂时搁置了该功能,但也积累了一些经验,将分两篇文章来写这部分的内容,欢迎交流! 关键字:Android动态加载 声明 欢迎转载, ...

  6. Rect

    判断给定的点是否被一个CGRect包含,可以用CGRectContainsPoint函数   BOOL contains = CGRectContainsPoint(CGRect rect, CGPo ...

  7. SMA2SATA、PCIe2SATA转换模块(也有叫:Sata Test Fixtures)

    SMA2SATA.PCIe2SATA测试夹具(Sata Test Fixtures) 去年制作SMA2SATA.PCIe2SATA适配器的过程早就想写出来,但一直没有时间,今天星期六有个空儿,简单整理 ...

  8. LESSCSS

    LESSCSS应需求而生 CSS 的语法相对简单,对使用者的要求较低,但同时也带来一些问题:CSS 需要书写大量看似没有逻辑的代码,不方便维护及扩展,不利于复用,尤其对于非前端开发工程师来讲,往往会因 ...

  9. thinkPHP中省市级联下拉列表

    公共函数放置位置common文件夹下common.php文件(此段代码也可放置在要使用的控制器中) 封装的下拉列表函数代码: /** * 根据列表拼装成一个下拉列表 ADD BY CK * @para ...

  10. Server2008R2:由于没有远程桌面授权服务器可以提供许可证,.....错误的解决 ---设计师零张

    一直使用远程桌面连接一台windows2008server服务器,今天突然报错,连不上了:   “由于没有远程桌面授权服务器可以提供许可证,远程会话被中断.请跟服务器管理员联系.”       由于是 ...