Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7ef2d31

Browse files
author
Tushar Roy
committed
Largest 3 non overlapping subarray of size k
1 parent 94942b0 commit 7ef2d31

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.interview.array;
2+
3+
import java.util.Arrays;
4+
import java.util.Deque;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
8+
/**
9+
*https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/description/
10+
*/
11+
public class MaximumSumThreeNonOverlappingSubarray {
12+
13+
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
14+
int sum = 0;
15+
int[] sumArray = new int[nums.length - k + 1];
16+
for (int i = 0; i < nums.length; i++) {
17+
if (i < k) {
18+
sum += nums[i];
19+
} else {
20+
sumArray[i - k] = sum;
21+
sum += nums[i];
22+
sum -= nums[i - k];
23+
}
24+
}
25+
sumArray[sumArray.length - 1] = sum;
26+
27+
int[][] dp = new int[4][sumArray.length + 1];
28+
29+
for (int i = 1; i <= 3; i++) {
30+
for (int j = 1; j <= sumArray.length; j++) {
31+
if (j >= k) {
32+
if (dp[i][j - 1] >= sumArray[j - 1] + dp[i - 1][j - k]) {
33+
dp[i][j] = dp[i][j - 1];
34+
} else {
35+
dp[i][j] = sumArray[j - 1] + dp[i - 1][j - k];
36+
}
37+
} else {
38+
if (dp[i][j - 1] >= sumArray[j - 1]) {
39+
dp[i][j] = dp[i][j - 1];
40+
} else {
41+
dp[i][j] = sumArray[j - 1];
42+
}
43+
}
44+
}
45+
}
46+
int[] output = new int[3];
47+
int j = dp[0].length - 1;
48+
for (int i = 3; i > 0;) {
49+
if (dp[i][j] == dp[i][j - 1]) {
50+
j--;
51+
} else {
52+
output[i - 1] = j - 1;
53+
i--;
54+
j = j - k;
55+
}
56+
}
57+
return output;
58+
}
59+
60+
public static void main(String[] args) {
61+
MaximumSumThreeNonOverlappingSubarray mss = new MaximumSumThreeNonOverlappingSubarray();
62+
int[] input = {3, 2, 2, 1, 1, 0, 5};
63+
int[] input1 = {1, 2, 1, 2, 6, 7, 5, 1};
64+
int[] output = mss.maxSumOfThreeSubarrays(input1, 2);
65+
for (int i : output) {
66+
System.out.println(i);
67+
}
68+
}
69+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /