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

首先我们定义一个数组: 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. hdu4405:概率dp

    题意: 总共有n+1个格子:0-n 初始情况下在 0号格子 每次通过掷骰子确定前进的格子数 此外 还有一些传送门可以瞬间从 u 点传送到 v 点(必须被传送) 求走到(或超过)n点总共需要掷多少次骰子 ...

  2. 集成Dubbo服务(Spring)

    Dubbo是什么? Dubbo是阿里巴巴SOA服务化治理方案的核心框架,每天为2,000+个服务提供3,000,000,000+次访问量支持,并被广泛应用于阿里巴巴集团的各成员站点. Dubbo[]是 ...

  3. 真实经纬度(gps)转成百度坐标的js方法

    转:http://www.360doc.com/content/16/0320/14/18636294_543805051.shtml 结果图: <!DOCTYPE html> <h ...

  4. hdu 3056 病毒侵袭持续中 AC自己主动机

    http://acm.hdu.edu.cn/showproblem.php?pid=3065 刘汝佳的模板真的非常好用,这道题直接过 学到: cnt数组记录单词出现次数 以及map存储单词编号与字符串 ...

  5. C++11中正則表達式測试

    VC++2010已经支持regex了, 能够用来编译下述代码. #include <string> #include <regex> #include <iostream ...

  6. DataBindings 与 INotifyPropertyChanged 实现自动刷新 WinForm 界面

    --首发于博客园, 转载请保留此链接  博客原文地址 业务逻辑与界面的分离对于维护与迁移是非常重要的,在界面上给某属性赋值,后台要检测到其已经发生变化 问题: 输入某物品 单价 Price, 数量Am ...

  7. Android调用系统邮件类应用的正确实现方法

    Android应用开发中,很多情况下免不了要调用手机上的邮件类应用,实现邮件发送的功能,这一般是通过调用系统已有的Intent来实现的.看到网上很多邮件发送都是调用action为android.con ...

  8. 验证docker的Redis镜像也存在未授权访问漏洞

    看到了这篇老外的博客:Over 30% of Official Images in Docker Hub Contain High Priority Security Vulnerabilities于 ...

  9. mysql连接提示1030

    今天上午,开发使用工具连上mysql,连接一个库,就提示 mysql 错误 ERROR 1030 Got error 28 from. 查询资料,说可能是磁盘空间不足.果然连上去一看/分区空间只有数十 ...

  10. Web App 前端构建(纯净版)

    asp.net 母版页: <!DOCTYPE html> <html> <head> <meta charset="utf-8" name ...