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 ...
随机推荐
- 文件夹65ad47d7-2e27-4a5c-b238-26643fdaeb98
这几天发现电脑中毒了,本地开的服务预览页面时,页面会被插入Html代码.我用360扫描之后发现有木马病毒(c:\programData有个65ad47d7-2e27-4a5c-b238-26643fd ...
- JavaScript 中的正常任务与微任务
正常情况下,JavaScript的任务是同步执行的,即执行完前一个任务,然后执行后一个任务.只有遇到异步任务的情况下,执行顺序才会改变. 这时,需要区分两种任务:正常任务(task)与微任务(micr ...
- (转)iOS Wow体验 - 第二章 - iOS用户体验解析(2)
本文是<iOS Wow Factor:Apps and UX Design Techniques for iPhone and iPad>第二章译文精选的第二部分,其余章节将陆续放出.上一 ...
- HTML5新增的一些属性和功能之八——web Worker
Web Workers 为什么用web workers? 浏览器的原理中决定了页面打开只有一个主线程--UI渲染线程,如果线程中有耗时的程序(js)会阻塞线程,使得页面中其他的UI无法渲染,我们一般把 ...
- Activity中的startActivityResult,setResult,finish,onActivityResult的关系
一:首先图示: 二:代码: 1:方法selectName public void selectName(View view){ Intent intent = new Intent(this,Name ...
- linux性能优化常用命令
作为一名linux系统管理员,最主要的工作是优化系统配置,使应用在系统上以最优的状态运行,但是由于硬件问题.软件问题.网络环境等的复杂性 和多变性,导致对系统的优化变得异常复杂,如何定位性能问题出在哪 ...
- [Angular 2] Injecting a Service
Using Services in Angular 2 is very simple. This lesson covers how to create a simple class as a Ser ...
- easyui combobox赋值
$('#cc').combobox('setValue','bitem3').combobox('setText','bitem3')
- Android下按钮的使用方法
package com.hangsheng.button; import android.app.Activity; import android.os.Bundle; import android. ...
- 工程与科学数值方法的Matlab实现
%stats.m function [mean,stdev]=stats(x) n=length(x);mean=sum(x)/n;stdev=sqrt(sum((x-mean).^2/(n-1))) ...