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

首先我们定义一个数组: 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. Permutations 解答

    Question Given a collection of numbers, return all possible permutations. For example,[1,2,3] have t ...

  2. Java代码编译和执行的整个过程

    Java代码编译是由Java源码编译器来完成,流程图如下所示: Java字节码的执行是由JVM执行引擎来完成,流程图如下所示: Java代码编译和执行的整个过程包含了以下三个重要的机制: Java源码 ...

  3. PyQt4--QPushButton阵列

    # -*- coding: utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * import sys import funct ...

  4. 推荐C/C++常见的面试题目

    http://blog.163.com/bingqingyujie..5/blog/static/75559361201011861958534/ 里面有详细的面试类型

  5. Mac OS X 下修改网卡地址和抵御 ARP 攻击

    用 Mac 系统有一段时间了,这里记录一下自己遇到的需要终端命令解决的问题. 网络环境绑定了原先机器的 MAC 地址,由于特殊原因,先把新机器的网卡地址改成原先那台. 在终端输入sudo ifconf ...

  6. Android开发有用的站点

    在github上面找到一个个人认为比較好的站点,好在能够方便下载开发工具.我的AndroidStudio就是在上面下载的.安装了一直在使用.该 网址主要收集整理Android开发所需的Android ...

  7. 【转载】cocos2d-x2.2.3和android的平台环境

    这两天试图按照教程来学习写游戏移植到的横版过关Android在.在网上找了很多教程,但版本号变化.所使用的工具有细微的差别.所以,现在我们还没有准备好,阅读后,下面的文章.最后能够顺利您的手机上跑起来 ...

  8. java基础之成员变量与局部变量

    成员变量的含义 局部变量的含义 成员变量与局部变量的区别

  9. String new赋值、直接赋值

    String类是final的.String str = new String("Hello"); //创建了两个对象系统会先创建一个匿名对象"Hello"存入堆 ...

  10. C++中cin输入类型不匹配解决方法

    #include <iostream> #include <set> using namespace std; int main() { int a; cin>>a ...