Learn-dsa..in 30 days!



























CC-14 : Find Maximum sum twins.

Description:

Given a DoubleLinkedList with integer data with size N nodes, node at index i and N-1-i are index twins. Find the index twins with maximum sum in the DoubleLinkedList.

Test cases and expected outputs:

Input Parameters Expected outputs
8->44->7->3->11->2->17->15->12->19 Maximum twin sum is : 56
8->44->8->44 Maximum twin sum is : 52
8->7 Maximum twin sum is : 15
8 Twin sum not possible

Pseudocode:

Check that the DoubleLinkedList has even number of nodes before progressing with these rest of the implementation.
Define variable of maxSum as maximumSum of twins that are found in DoubleLinkedList.
Define variable forwNode as firstNode of DoubleLinkedList and variable revNode as lastNode of the DoubleLinkedList.
Next set of twins can be found by forwNode.nextNode and revNode.prevNode.
Repeat below steps for twins in the DoublLinkedList:
forwNode and revNode are twins, store the sum of their node data in currSum.
If currSum > maxSum, then set maxSum to currSum.
After all twins are compared maxSum will contain the maximum possible sum of twins in the DoubleLinkedList.

Code:

public int doubleLinkedListMaximumSumTwin(DoubleLinkedList doubleLinkedList) throws Exception{
	if (doubleLinkedList.getFirstNode()==null) { return Integer.MIN_VALUE;}
	int cnt= doubleLinkedList.getSize(); int idx=0;
	int currSum=0; int maxSum=0;
	if (cnt % 2 != 0) { return Integer.MIN_VALUE;}
	DoubleLinkedListNode forwNode=doubleLinkedList.getFirstNode();
	DoubleLinkedListNode revNode=doubleLinkedList.getLastNode();
	while (idx <= cnt/2-1) {
		currSum=forwNode.getNodeData()+revNode.getNodeData();
		if (currSum > maxSum) {
			maxSum=currSum;
		}
		idx++;
		forwNode=forwNode.getNextNode();
		revNode=revNode.getPreviousNode();
	}	
	return maxSum;
}

Click here to download and run code and test cases !