You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classListNode {
intval;
ListNodenext;
ListNode(intval) {
this.val = val;
this.next = null;
}
}
publicclassFloydCycleDetection {
publicstaticbooleanhasCycle(ListNodehead) {
if (head == null || head.next == null) {
returnfalse; // No cycle if head is null or only one node exists
}
ListNodeslow = head; // Slow pointer moves one step at a timeListNodefast = head; // Fast pointer moves two steps at a timewhile (fast != null && fast.next != null) {
slow = slow.next; // Move slow pointer one stepfast = fast.next.next; // Move fast pointer two stepsif (slow == fast) {
returntrue; // Cycle detected if slow and fast pointers meet
}
}
returnfalse; // No cycle found
}
publicstaticvoidmain(String[] args) {
// Create a linked list with a cycleListNodehead = newListNode(1);
ListNodenode2 = newListNode(2);
ListNodenode3 = newListNode(3);
ListNodenode4 = newListNode(4);
ListNodenode5 = newListNode(5);
head.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node2; // Cycle: node5 points back to node2System.out.println("Does the linked list have a cycle? " + hasCycle(head));
}
}
Kadane's Algorithm
publicclassKadanesAlgorithm {
publicstaticintmaxSubArraySum(int[] nums) {
intmaxSum = nums[0]; // Initialize maxSum with the first element of the arrayintcurrentSum = nums[0]; // Initialize currentSum with the first element of the arrayfor (inti = 1; i < nums.length; i++) {
/** Calc the currentSum for the current element by taking the maximum of the current element itself or the sum of the current element and the previous subarray sum **/currentSum = Math.max(nums[i], currentSum + nums[i]);
/**Update the maxSum with the maximum of the currentSum and the previous maxSum * * **/maxSum = Math.max(maxSum, currentSum);
}
returnmaxSum; // Return the maximum subarray sum
}
publicstaticvoidmain(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
intmaxSum = maxSubArraySum(nums);
System.out.println("Maximum subarray sum: " + maxSum);
}
}