
For this problem, you will implement divide and conquer
2.
Maximum Subarray using Divide and Conquer
Create a class called MaxSubFinder in the divideandconquer package. This class will
implement the maximum subarray problem on a linked list using the
pseudocode described above. Implement the following methods with the exact signatures
below. You will need to create private helper methods to do most of the work. You can
assume that the list are not empty.
public static Triple<Node,Node,Integer> getMaxSubList(LinkedList list)
This method returns a triple that represents the maximum sub list. The first element of the
triple is the list node where the maximum sublist starts, the middle element of the triple is
the list node where the maximum sublist ends, and the last element of the triple is the
maximum sublist sum .
Triple class:
package divideandconquer;
public class Triple<First,Middle,Last> {
First first;
Middle middle;
Last last;
public Triple(First first, Middle middle, Last last) {
this.first= first;
this.middle = middle;
this.last = last;
}
public First getFirst() {
return first;
}
public void setFirst(First first) {
this.first = first;
}
public Middle getMiddle() {
return middle;
}
public void setMiddle(Middle middle) {
this.middle = middle;
}
public Last getLast() {
return last;
}
public void setLast(Last last) {
this.last = last;
}
}
LinkedList Class:
![Maximum Subarray
findMaxSubarry (arr, low, high)
if high-low
else
return (low high, arr [low])
mid= mid point of arr
(1-low, 1-high, 1-sum)
(r-low, r-high, r-sum)
(c-low, c-high, c-sum)
if 1-sum 2 r-sum and
else
findMaxCrossing (arr, low, mid, high)
1-sum = MIN
0
sum =
for i mid downto low
sum = sum arr[i]
if sum > 1-sum
return (1-low, l-high, 1-sum)
else if r-sum ≥l-sum and r-sum ≥c-sum
return (r-low, r-high, r-sum)
return (c-low, c-high, c-sum)
MIN
1-sum = sum
max-left
r-sum =
sum =
0
for j=mid+1 to high
=
i
low, mid)
mid+1, high)
findMaxCrossing (arr, low, mid, high)
1-sum 2 c-sum
sum = sum + arr[j]
if sum > r-sum
=
=
findMaxSubarray(arr,
findMaxSubarray(arr,
=
r-sum sum
max-right = j
return (max-left, max-right, 1-sum+r-sum);](https://content.bartleby.com/qna-images/question/165f5551-99fc-4800-9810-1597ce53807c/f14eac02-1e41-480d-aebb-0e7f8ef9f2f3/2kk5div_thumbnail.png)

Trending nowThis is a popular solution!
Step by stepSolved in 3 steps

In the following code, it errors at
/ Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
Code:
publicstatic Triple<Node,Node,Integer> getMaxSubList(LinkedListlist) {
// If the list is null or empty, return a Triple with all values set to 0
if (list == null || list.isEmpty()) {
returnnew Triple(0, 0, 0);
}
// Call the private helper method to find the maximum subarray
returnfindMaxSubList(list, 0, list.size() - 1);
}
// This is a recursive helper method that divides the list into smaller subarrays
// and finds the maximum subarray of each subarray. It then combines these maximum subarrays
// to find the maximum subarray of the entire list.
privatestaticTriple findMaxSubList(LinkedListlist, intlow, inthigh) {
// Base case: if the subarray has only one element, return that element as the maximum subarray
if (low == high) {
returnnew Triple(low, high, list.get(low));
}
// Calculate the middle index of the subarray
intmid = (low + high) / 2;
// Recursively find the maximum subarray of the left and right halves of the subarray,
// and the maximum subarray that crosses the middle of the subarray
Tripleleft = findMaxSubList(list, low, mid);
Tripleright = findMaxSubList(list, mid + 1, high);
Triplecross = findMaxCrossingList(list, low, mid, high);
// Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
}
// This method finds the maximum subarray that crosses the middle of the subarray
privatestaticTriple findMaxCrossingList(LinkedList<Integer> list, intlow, intmid, inthigh) {
// Initialize variables to keep track of the maximum sum on the left and right sides of the middle
intleftSum = Integer.MIN_VALUE;
intrightSum = Integer.MIN_VALUE;
// Initialize variables to keep track of the starting and ending indices of the maximum subarray
intmaxLeft = 0;
intmaxRight = 0;
// Find the maximum sum on the left side of the middle
intsum = 0;
for (inti = mid; i >= low; i--) {
sum += list.get(i);
if (sum > leftSum) {
leftSum = sum;
maxLeft = i;
}
}
// Find the maximum sum on the right side of the middle
sum = 0;
for (intj = mid + 1; j <= high; j++) {
sum += list.get(j);
if (sum > rightSum) {
rightSum = sum;
maxRight = j;
}
}
// Return a Triple with the starting and ending indices of the maximum subarray that crosses the middle,
// and the sum of the maximum subarray
returnnew Triple(maxLeft, maxRight, leftSum + rightSum);
}
I get an error at the followinf code.. it says >= is undefined for the argument type.
// Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
i get 2 errors at the following line. How do i correct?
public static Triple getMaxSubList(LinkedList<Integer> list) {
-The type LinkList is not generic; it can't be parameterized with arguments <Integer>
-Triple is a raw type, references to eneric tye Triple <First, Middle, Last> should be parameterized
can you help with the code for getMaxSubList as well?
In the following code, it errors at
/ Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
Code:
publicstatic Triple<Node,Node,Integer> getMaxSubList(LinkedListlist) {
// If the list is null or empty, return a Triple with all values set to 0
if (list == null || list.isEmpty()) {
returnnew Triple(0, 0, 0);
}
// Call the private helper method to find the maximum subarray
returnfindMaxSubList(list, 0, list.size() - 1);
}
// This is a recursive helper method that divides the list into smaller subarrays
// and finds the maximum subarray of each subarray. It then combines these maximum subarrays
// to find the maximum subarray of the entire list.
privatestaticTriple findMaxSubList(LinkedListlist, intlow, inthigh) {
// Base case: if the subarray has only one element, return that element as the maximum subarray
if (low == high) {
returnnew Triple(low, high, list.get(low));
}
// Calculate the middle index of the subarray
intmid = (low + high) / 2;
// Recursively find the maximum subarray of the left and right halves of the subarray,
// and the maximum subarray that crosses the middle of the subarray
Tripleleft = findMaxSubList(list, low, mid);
Tripleright = findMaxSubList(list, mid + 1, high);
Triplecross = findMaxCrossingList(list, low, mid, high);
// Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
}
// This method finds the maximum subarray that crosses the middle of the subarray
privatestaticTriple findMaxCrossingList(LinkedList<Integer> list, intlow, intmid, inthigh) {
// Initialize variables to keep track of the maximum sum on the left and right sides of the middle
intleftSum = Integer.MIN_VALUE;
intrightSum = Integer.MIN_VALUE;
// Initialize variables to keep track of the starting and ending indices of the maximum subarray
intmaxLeft = 0;
intmaxRight = 0;
// Find the maximum sum on the left side of the middle
intsum = 0;
for (inti = mid; i >= low; i--) {
sum += list.get(i);
if (sum > leftSum) {
leftSum = sum;
maxLeft = i;
}
}
// Find the maximum sum on the right side of the middle
sum = 0;
for (intj = mid + 1; j <= high; j++) {
sum += list.get(j);
if (sum > rightSum) {
rightSum = sum;
maxRight = j;
}
}
// Return a Triple with the starting and ending indices of the maximum subarray that crosses the middle,
// and the sum of the maximum subarray
returnnew Triple(maxLeft, maxRight, leftSum + rightSum);
}
I get an error at the followinf code.. it says >= is undefined for the argument type.
// Return the maximum subarray among the left, right, and cross subarrays
if (left.getLast() >= right.getLast() && left.getLast() >= cross.getLast()) {
returnleft;
} else if (right.getLast() >= left.getLast() && right.getLast() >= cross.getLast()) {
returnright;
} else {
returncross;
}
i get 2 errors at the following line. How do i correct?
public static Triple getMaxSubList(LinkedList<Integer> list) {
-The type LinkList is not generic; it can't be parameterized with arguments <Integer>
-Triple is a raw type, references to eneric tye Triple <First, Middle, Last> should be parameterized
can you help with the code for getMaxSubList as well?
- I need answer quicklyarrow_forward// Only few methods are mentioned here //Do remaining methods to pass the test methods /*** Removes the specified (num) of the given element from the internal ArrayList of elements. * If num <= 0, don't remove anything. * If num is too large, remove all instances of the given element from the internal ArrayList of elements.* Example:* - For a defined CustomIntegerArrayList containing the integers: 1, 2, 1, 2, 1* - Calling remove(2, 1) would remove the first 2 instances of 1 * - The CustomIntegerArrayList will then contain the integers: 2, 2, 1* - For a defined CustomIntegerArrayList containing the integers: 100, 100, 100 * - Calling remove(4, 100) would remove all instances of 100 * - The CustomIntegerArrayList will then be empty* - For a defined CustomIntegerArrayList containing the integers: 5, 5, 5, 5, 5 * - Calling remove(0, 5) would remove nothing* * @param num number of instances of element to remove * @param element to remove*/ public void remove(int num, int element) {//…arrow_forwardIn this project, you will implement a Set class that represents a general collection of values. For this assignment, a set is generally defined as a list of values that are sorted and does not contain any duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that e1.equals(e2) and no null elements. (in java)Requirements among all implementations there are some requirements that all implementations must maintain. • Your implementation should always reflect the definition of a set. • For simplicity, your set will be used to store Integer objects. • An ArrayList<Integer> object must be used to represent the set. • All methods that have an object parameter must be able to handle an input of null. • Methods such as Collections. the sort that automatically sorts a list may not be used. Instead, when a successful addition of an element to the Set is done, you can ensure that the elements inside the ArrayList<Integer>…arrow_forward
- public class PokerAnalysis implements PokerAnalyzer { privateList<Card>cards; privateint[]rankCounts; privateint[]suitCounts; /** * The constructor has been partially implemented for you. cards is the * ArrayList where you'll be adding all the cards you're given. In addition, * there are two arrays. You don't necessarily need to use them, but using them * will be extremely helpful. * * The rankCounts array is of the same length as the number of Ranks. At * position i of the array, keep a count of the number of cards whose * rank.ordinal() equals i. Repeat the same with Suits for suitCounts. For * example, if your Cards are (Clubs 4, Clubs 10, Spades 2), your suitCounts * array would be {2, 0, 0, 1}. * * @param cards * the list of cards to be added */ publicPokerAnalysis(List<Card>cards){ this.cards=newArrayList<Card>(); this.rankCounts=newint[Rank.values().length]; this.suitCounts=newint[Suit.values().length];…arrow_forwardJava Complete a method calledRedundantCharacterMatch(ArrayList<Character> YourFirstName): the parameter of this method is an ArrayList<Character> whose elements are the characters in your first name (they should be in the order appear in your first name, e.g., if your first name is bob, then the ArrayList<Char> includes ‘b’, ‘o’, ‘b’.). The method will check whether there exists duplicate characters in your name and return the index of those duplicate characters. For example, when using bob as first name, it will return b: 0, 2. 2. Create an ArrayList<Character> NameExample. All the characters of your first name will appear twice in this ArrayList. For example, if your first name is bob, then NameExample will include the following element {b,o,b,b,o,b}. Then, please use NameExample as parameter for the method RedundantCharacterMatch(). If your first name is bob, the results that print in the console will be b: 0, 2, 3, 5 o: 1, 4arrow_forwardIn this project you will implement a Set class which represents a general collection of values. For this assignment, a set is generally defined as a list of values that is sorted and does not contain any duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that e1.equals(e2) and no null elements. Requirements To ensure consistency among all implementations there are some requirements that all implementations must maintain. • Your implementation should reflect the definition of a set at all times. • For simplicity, your set will be used to store Integer objects. • An ArrayList object must be used to represent the set. • All methods that have an object parameter must be able to handle an input of null. • Methods such as Collections.sort that automatically sort a list may not be used. • The Set class shall reside in the default package. Recommendations There are deviations in program implementation that are acceptable and will not impact the overall…arrow_forward
- Without using the java collections interface (i.e. do not import java.util.List, LinkedList, etc. ) Write a java program that inserts a new String element (String newItem) into a linked list before another specified item (String itemToInsertBefore). For example if items "A", "B", "C" and "D" are in a linked list in that order and the below method is called, insertBefore("E", "C"), then "E" would be inserted before "C", making the final list to be "A", "B", "E", "C" and "D" with no nulls or blank elements or any elements missing or anything. It should work for all lenghths of linkedlists of Strings. public Boolean insertBefore(String newItem, String itemToInsertBefore) { // returns true if done successfully, else returns false if itemToInsertBefore cannot be found or some other error }arrow_forwardIn the existing CircularlyLinkedList class, Write a non-static method named getMax for finding the maximum element in a circularly linked list. Write the testing code in the main method of the class CircularlyLinkedList. For this purpose, you must only use and update the CircularlyLinkedList.java file provided in Lesson3Examples posted in the eCentennialmodule "Lesson Examples (from textbook)" package exercise3; public class CircularlyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> tail = null; private int size = 0; public CircularlyLinkedList() { } public int size() { return size; } public boolean isEmpty() { return size == 0; } public E first() { if (isEmpty()) return null; return…arrow_forwardHello!I'm currently in the process of developing an algorithm for a reverse method for a singly-linked list--not an array, which is a much easier algorithm and I have done before. I'm writing in Java. I'm working from a pre-written SinglyLinkedList class with certain methods (intentionally) empty, for us to fill.I have, unbelievably, spent somewhere around 5 hours going through drafts. The easiest implementation I've conceived of would be to create a second list with which to import the nodes and elements starting from the tail. public void reverse() {<Integer> list2 = new SinglyLinkedList();for (size) { list2.addLast(tail); list1.remove(tail); }}This is the rough draft pseudocode for the aforementioned implementation.If we were to work within the same list, instead of creating a new one we would have to go through, for a size of 10, a hundred iterations. Obviously, there are a number of problems.First, reverse() has been defined as a void method. It's not supposed to return…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





