This repository contains solutions to five algorithmic problems, each requiring a unique approach, from dynamic programming to binary search. Below is a brief overview of each solution.
- Binary search on the possible power limit.
- Initialize
left = 0
,right = max power supply (ci)
. - Adjust
mid
based on computed power values. - Stopping condition:
min1 == min2
, meaning we've maximised the power supply.
O(log n) – binary search ensures efficient convergence.
- Utilizes modular exponentiation (
fastPow
) for efficiency. - Six cases based on
H
(horizontal) andV
(vertical) positioning. - Uses two coefficient arrays to store values dynamically.
- Smartly applies multiplication rules based on previous character positioning.
O(n) – single-pass computation.
- Read two sequences and use two indices to traverse them simultaneously.
- Track sums with
sum1
andsum2
, and use flags (search
,case1
,case2
) to handle sub-sequence sums efficiently. - Two main cases:
- Sum elements from the second sequence to match an element in the first.
- Sum elements from the first sequence to match an element in the second.
- If sequences can't be compressed properly, output
-1
.
O(max(n, m)) – as we traverse both sequences linearly.
- Calculate letter frequency per word.
- Sort words based on:
- Descending frequency.
- Frequency-to-length ratio.
- Longer words preferred for ties.
- Select words greedily to maximise encryption efficiency.
- Repeat for each letter (
a-z
) and track the maximum encrypted length.
O(N²) – due to nested sorting and frequency checks.
- Uses dynamic programming (
dp[i]
) to track the minimum price at stepi
. - Three options at each step:
- Buy normally (
dp[i - 1] + prices[i]
). - Use a 2-product offer (
dp[i - 2] + discounted sum
). - Use a 3-product offer (
dp[i - 3] + best discount
).
- Buy normally (
- Stores optimal previous results to ensure minimum cost.
O(n) – processes each price efficiently.
To test the programs, create input files manually and use the Makefile rules. Here are sample test cases for each problem:
-
Server Power (server.cpp)
- Input:
4
6 9 7 5
2 4 1 8
- Expected Output:
2.5
-
Coloring
- Input:
2
1 H 1 V
- Expected Output:
6
-
Compression
- Input:
6
11 2 2 1 8 6
7
3 8 2 1 2 11 3
- Expected Output:
4
-
Encryption
- Input:
4
too
otter
tote
oo
- Expected Output:
9
-
Offer
- Input:
5 1
80 27 10 20 300
- Expected Output:
413.5
Problem | Approach | Complexity |
---|---|---|
Server | Binary search | O(log n) |
Coloring | Modular exponentiation | O(n) |
Compression | Two-pointer traversal | O(max(n, m)) |
Encryption | Sorting + Greedy Selection | O(N²) |
Offer | Dynamic programming | O(n) |
Each solution leverages a tailored algorithmic strategy to optimise performance.
This project is licensed under the MIT Licence. See the LICENCE file for further details.