0% found this document useful (0 votes)
8 views13 pages

22BCS10271 Harsh Thakur Assignment

The document outlines a series of programming assignments in Computer Science and Engineering, focusing on algorithms for various problems such as maximum subarray sum after operations, minimum number of platforms for trains, next greater element in a circular array, decoding a string, and reordering a linked list. Each problem includes an aim, objective, algorithm, implementation code, and outputs. Additionally, it highlights the learning outcomes from these assignments, emphasizing techniques like greedy logic, sorting, two-pointer methods, and stack usage.

Uploaded by

rc2899318
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

22BCS10271 Harsh Thakur Assignment

The document outlines a series of programming assignments in Computer Science and Engineering, focusing on algorithms for various problems such as maximum subarray sum after operations, minimum number of platforms for trains, next greater element in a circular array, decoding a string, and reordering a linked list. Each problem includes an aim, objective, algorithm, implementation code, and outputs. Additionally, it highlights the learning outcomes from these assignments, emphasizing techniques like greedy logic, sorting, two-pointer methods, and stack usage.

Uploaded by

rc2899318
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Assignment-1
Student Name: Harsh Thakur UID:22BCS10271 Branch: CSE Date of
Performance:31/05/25Subject Name:In-house Training Semester : 6

1. Aim: Problem 1. Maximum Subarray Sum after Operations Problem Statement:


You are given an array of integers and a set of operationswhere each operation allows
you to either add a given value to an element orleaveit unchanged. Your task is to find
the maximum possible sumof a subarrayafterperforming exactly k operations.

2. Objective:
Given an array and a list of operations (values you can add), applyexactlykoperations
(one per value) to maximize the sumof any subarray. Eachoperation can be added
to only one element of the array.

3. Algorithm:

∙ Sort operations in descending order (to use bigger boosts first).

∙ For each operation, try adding it to every unused index and checkwhichposition
gives the maximum Kadane’s subarray sum.

∙ Apply the operation at the best index, and repeat for the next operation.

∙ Finally, use Kadane's Algorithm to return the maximumsubarraysumfrom


the modified array.

4. Implementation/Code:
import java.util.*;
public class Main {
static int kadane(int[] arr) {
int maxEndingHere = arr[0];
int maxSoFar = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]); maxSoFar =
Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


}

public static int maxSubarraySumWithOperations(int[] arr, int[] operations){


int n = arr.length;
int k = operations.length;
int[] modifiedArr = Arrays.copyOf(arr, n);
boolean[] usedIndex = new boolean[n];
Arrays.sort(operations);
for (int i = k - 1; i >= 0; i--)
{ int op = operations[i];
int bestIndex = -1;
int bestGain = Integer.MIN_VALUE;
for (int j = 0; j < n; j++) {
if (usedIndex[j]) continue;
int original = modifiedArr[j];
modifiedArr[j] += op;
int gain = kadane(modifiedArr);
modifiedArr[j] = original;
if (gain > bestGain)
{ bestGain = gain;
bestIndex = j;
}
}
if (bestIndex != -1)
{ modifiedArr[bestIndex] += op;
usedIndex[bestIndex] = true;
}
}
return kadane(modifiedArr);
}

public static void main(String[] args)


{ int[] arr = {1, 2, -3, 4, -5};
int[] operations = {3, 1};

System.out.println("Original Array: " + Arrays.toString(arr));


System.out.println("Operations Available: " +
Arrays.toString(operations));

int result = maxSubarraySumWithOperations(arr, operations); System.out.println("

Maximum Subarray Sum After Applying Operations=


Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


" + result);
}
}

5. Output:
Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

1. Aim:Problem 2:Minimum Number of Platforms Given the arrival and


departure times of trains, determine theminimumnumber of platforms required
at the station so that no trainwaits.

1. Objective:Given arrival and departure times of n trains, findtheminimum


number of platforms needed so that no train has towait.
2. Algorithm:
∙ Sort both arrival and departure arrays.

∙ Use two pointers: one for arrival and one for departure. ∙ If a train arrives before the

last one departs, increase platformcount. ∙ If a train departs before the next arrives,

decrease platformcount. ∙ Track the maximum platforms used at any time —that’s

the answer.

3. Implementation/Code:
import java.util.*;
public class Main {
public static int findMinimumPlatforms(int[] arr, int[] dep) {
Arrays.sort(arr);
Arrays.sort(dep);
int n = arr.length;
int i = 1, j = 0;
int platforms = 1, maxPlatforms = 1; while (i < n && j < n)
{
if (arr[i] <= dep[j])
{ platforms++;

Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


i++;
} else {
platforms--;
j++;
}
maxPlatforms = Math.max(maxPlatforms, platforms);
}
return maxPlatforms;
}
public static void main(String[] args) {
int[] arr = {900, 940, 950, 1100, 1500, 1800};
int[] dep = {910, 1200, 1120, 1130, 1900, 2000};
int result = findMinimumPlatforms(arr, dep);
System.out.println("Arrival Times: " + Arrays.toString(arr));
System.out.println("Departure Times: " + Arrays.toString(dep));
System.out.println(" Minimum Platforms Required =" +result);}
}

4.Output:

Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


1. Aim:Problem 3: Next Greater Element II
Given a circular array (the next element of the last element is the first elementof the
array), find the next greater number for every element in the array. Thenext greater
number of a number x is the first greater number to its traversing-order next in the array,
which means you could search circularly tofinditsnextgreater number. If it doesn't exist,
return -1 for this number.

2. Objective:
Find the next greater element for each element in a circular array; if
noneexists,return -1.

3. Algorithm:

∙ Initialize a stack to store indices and a result array filled with-1. ∙ Traverse the

array twice (0 to 2*n - 1) to simulate circularity. ∙ For each element nums[i %

n]:

∙ While stack is not empty and current element > element at stack’stopindex,

Pop from stack and update result at that index with current element. ∙ If in the

first pass (i < n), push current index onto the stack.

∙ After traversal, result array contains the next greater elements or -1ifnone exists.

4. Implementation/Code:
class Solution {
public int[] nextGreaterElements(int[] nums)
{ int n = nums.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();

Arrays.fill(result, -1);
Harsh Thakur 22BCS10271

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

for (int i = 0; i < 2 * n; i++)


{ int num = nums[i % n];

while (!stack.isEmpty() && nums[stack.peek()] < num) {


result[stack.pop()] = num;
}

if (i < n)
{ stack.push(i);
}
}

return result;
}
}
5. Output:
Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


1. Aim:Problem 4: Decoding string
Given an encoded string, return its decoded string. The encodingruleis:k[encoded
string], where the encoded string inside the square brackets isbeingrepeated exactly k
times. You may assume that the input string is alwaysvalid.

2. Objective:
Decode a string encoded with the pattern k[encoded_string] where thesubstringinside
brackets is repeated k times. Return the fully decoded string.

3. Algorithm:
1. Use two stacks — one for counts and one for partial decoded strings. 2. Traverse the
input string character by character:
If digit, build the repeat count k.
If [, push the current count and current decoded string ontotheir stacks,reset
current and k.
If ], pop count and previous decoded string; append the current
decodedsubstring repeated count times to it.
Else, append characters to current decoded substring.
3. At the end, the current string contains the fully decoded string.

4. Implementation/Code:Problem 4: Queue Using Two Stacksclass Solution {


public String decodeString(String s)
{ Stack<Integer> counts = new Stack<>();
Stack<StringBuilder> resultStack = new Stack<>(); StringBuilder
current = new StringBuilder();
int k = 0;

for (char ch :s.toCharArray())


{ if (Character.isDigit(ch)) {
k = k * 10 + (ch - '0');
} else if (ch == '[')
{ counts.push(k);
resultStack.push(current);
current = new StringBuilder();
k = 0;
} else if (ch == ']') {
Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


StringBuilder decodedString = resultStack.pop();
int count = counts.pop();
for (int i = 0; i < count; i++)
{ decodedString.append(current);
}
current = decodedString;
} else {
current.append(ch);
}
}

return current.toString();
}
}

5. Output:
Harsh

Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


1. Aim:Problem 5. Reorder List
Problem Statement: Given a singly linked list L:
L0→L1→…→Ln-1→Ln,reorder it to:
L0→Ln→L1→Ln-1→L2→Ln-2→…

2. Objective:Reorder a singly linked list in the pattern:L0 →Ln→L1→Ln-1 →


L2 → Ln-2 → ...without using extra space.

3. Algorithm:

. Find the middle of the linked list using slow and fast pointers. . Reverse the

second half of the list starting fromthe middle’s next node.

. Merge the two halves by alternating nodes fromthe first


andreversedsecond half.
4. Implementation/Code:

class Solution {
public void reorderList(ListNode head) { if (head == null ||
head.next == null) return;

ListNode slow = head, fast = head;


while (fast != null && fast.next != null)
{ slow = slow.next;
fast = fast.next.next;
}

ListNode prev = null, curr = slow.next;


slow.next = null;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
Harsh Thakur 22BCS10271

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

ListNode first = head,second = prev;


while (second != null) {
ListNode temp1 = first.next, temp2 = second.next; first.next =
second;
second.next = temp1;
first = temp1;
second = temp2; } }}
6.Output:

7. Learning Outcome:
1. Learned how to strategically apply limited operations to optimize subarraysumusing
greedy logic + prefix sum + priority decisions.

2. Understood how to handle overlapping intervals using sorting and twopointers, acommon
technique in scheduling and time-based event problems.

3. Mastered use of monotonic stack and how to simulate circular arrays efficientlyusing
modulo and two-pass traversal.

4. Learned how to use two stacks (one for numbers, one for strings) to decodenestedpatterns
– useful in parsing and expression evaluation problems.

Harsh Thakur 22BCS10271

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy