Sort with maximum of given swaps - sorting

I'm solving a problem which requires to sort an array. An array with size n can contain elements from 1 to n.
We are given an array and m number of swaps. we have to sort that array by using given swaps and own swap, in such a way we use minimum of own swaps...
Example..
Array 3 1 4 2
Given swaps 1 2
Here first we can perform given swap...array become 1 3 4 2 now we can use own swaps 2 ,4 and 3, 4...(1,2 and 3,4 are indexes)
So answer here is 2 because only own swaps are counted and we need to minimise it

Related

maximum number of subarrays that contains both maximum and minimum elements of a resultant array

You are given an array of n elements you allowed to delete at max one element from provided array. The order of elements remain the same .you are required to maximize the number of subarrays that contain both maximum and minimum element of the resultant array . A subarrays is the sequence of consecutive element of the array
Input
T no of test case
N size of array
N array element
Output
For each test case print one single integer the maximum number of subarrays that contains both maximum and minimum elements of the resultant array
Examples
4
6
7 2 5 4 3 1
7
1 2 3 4 5 6 7
6
2 5 3 2 5 5
4
5 5 5 5
Output
4
1
12
15
Test case 1 explanation
If we delete 1 from the array then the resultant array will be 7 2 5 4 3
So the number of subarrays will contains max 7 and minimum 2 will be 4
[7,2]
[7,2,5]
[7,2,5,4]
[7,2,5,4,3]
Do some math. If the min and max elements are at the indices i and j (does not matter who is where, just i < j), the number of subarrays is (i + 1) * (len - j). Prove this fact, or at least convince yourself that it is so.
Now, prove (or at least convince yourself) that it doesn't make sense to remove any element other than min or max.
I hope that this is enough to get you started.

Algorithm to find the m smallest numbers in a list of n numbers

I have to write an algorithm to find the "m smallest numbers in a list of n numbers". I don't understand what this line means. Do I have to find all the smallest numbers in a list and print them. For example if I have a list of say 4 elements [10, 20, 30, 40], do I have to print every number smaller than 40 one iteration at a time. Or is there some other meaning that's eluding me.
What they're asking is this: given a list of n numbers, find the m smallest numbers. So if n = 10 and m = 5 and the list is this:
Input: 1 4 2 6 3 6 2 4 6 1
Output: 1 1 2 2 3
A solution to this problem is to populate a max-heap with the first m numbers from the collection of n numbers. Then, go through the remaining n-m numbers in the list and compare to the max of the max-heap. If the number from the list is less than the max of the max list, remove the max from the max list and replace it with the current number from the list. Repeat until all numbers have been checked and then return the items in the m-heap.
The complexity of this is O(nlogm) since you do potentially one remove and one insert for each of the (n-m) elements in the list after taking the first m to prime the max heap.
What I understand, is that you have to write a function, that takes as parameter a number m, and return an array of number, which is of size m, and contains the m smallest numbers.
Taking your example, if we say that m is 2, we will return an array of 2 elements, containing the 2 smallest elements : [10,20]
If we set m to 3, the function would return [10,20,30]

Generate a list of permutations paired with their number of inversions

I'm looking for an algorithm that generates all permutations of a set. To make it easier, the set is always [0, 1..n]. There are many ways to do this and it's not particularly hard.
What I also need is the number of inversions of each permutation.
What is the fastest (in terms of time complexity) algorithm that does this?
I was hoping that there's a way to generate those permutations that produces the number of inversions as a side-effect without adding to the complexity.
The algorithm should generate lists, not arrays, but I'll accept array based ones if it makes a big enough difference in terms of speed.
Plus points (...there are no points...) if it's functional and is implemented in a pure language.
There is Steinhaus–Johnson–Trotter algorithm that allows to keep inversion count easily during permutation generation. Excerpt from Wiki:
Thus, from the single permutation on one element,
1
one may place the number 2 in each possible position in descending
order to form a list of two permutations on two elements,
1 2
2 1
Then, one may place the number 3 in each of three different positions
for these three permutations, in descending order for the first
permutation 1 2, and then in ascending order for the permutation 2 1:
1 2 3
1 3 2
3 1 2
3 2 1
2 3 1
2 1 3
At every step of recursion we insert the biggest number in the list of smaller numbers. It is obvious that this insertion adds M new inversions, where M is insertion position (counting from the right). For example, if we have 3 1 2 list (2 inversions), and will insert 4
3 1 2 4 //position 0, 2 + 0 = 2 inversions
3 1 4 2 //position 1, 2 + 1 = 3 inversions
3 4 1 2 //position 2, 2 + 2 = 4 inversions
4 3 1 2 //position 3, 2 + 3 = 5 inversions
pseudocode:
function Generate(List, Count)
N = List.Length
if N = N_Max then
Output(List, 'InvCount = ': Count)
else
for Position = 0 to N do
Generate(List.Insert(N, N - Position), Count + Position)
P.S. Recursive method is not mandatory here, but I suspect that it is natural for functional guys
P.P.S If you are worried about inserting into lists, consider Even's speedup section that uses only exchange of neighbour elements, and every exchange increments or decrements inversion count by 1.
Here is an algorithm that does the task, is amortized O(1) per permutation, and generates an array of tuples of linked lists that share as much memory as they reasonably can.
I'll implement all except the linked list bit in untested Python. Though Python would be a bad language for a real implementation.
def permutations (sorted_list):
answer = []
def add_permutations(reversed_sublist, tail_node, inversions):
if (0 == len(sorted_sublist)):
answer.append((tail_node, inversions))
else:
for idx, val in enumerate(reversed_sublist):
add_permutations(
filter(lambda x: x != val),
ListNode(val, tail_node,
inversions + idx
)
add_permutations(reversed(sorted_list), EmptyListNode(), 0)
return answer
You might wonder at my claim of amortized O(1) work with all of this copying. That's because if m elements are left we do O(m) work then amortize it over m! elements. So the amortized cost of the higher level nodes is a converging cost per bottom call, of which we need one per permutation.

algorithm: select a number from each list, find the largest sum

if we have n lists, we need to select a number from each list, the selected number cannot be selected again, how to make selection to get the largest sum of n selected numbers?
e.g.
list1: 4 5 7.
list2: 3 5 7.
list3: 1 5
if we select 7 from list1, the largest number we can select in list 2 is 5(because same number cannot be selected twice), if we select 5 from list2, we can only select 1 from list3, so the sum is 7+5+1=13
it is NOT the best selection. however, if we select 4 from list1, 7 from list2, 5 from list3, the sum is 4+7+5=16
Is there a algorithm to find the best way to make selection in order to get the largest sum?
The solution should be perfect.
There is no direct algorithm for it, however, the problem can be solved in a polynomial time by modifying Hungarian Algorithm. WIKI
We are given a nonnegative n×n matrix, where the element in the i-th
row and j-th column represents the cost of assigning the j-th job to
the i-th worker. We have to find an assignment of the jobs to the
workers that has minimum cost. If the goal is to find the assignment
that yields the maximum cost, the problem can be altered to fit the
setting by replacing each cost with the maximum cost subtracted by the
cost.
Construct the matrix of dimension (K*K), where K=max(n,maximum number of elements in a list).
For example:
List 1=1 2 3 4
List 2=5
List 3=9 10
The K*K matrix is:
1 2 3 4
5 0 0 0
9 10 0 0
0 0 0 0
Apply the following Algorithm http://en.wikipedia.org/wiki/Hungarian_algorithm#Setting to the above matrix.
Since we have sorted lists and all members of the list is positive, the largest number of one of the list should be in the result list. You should also assume that the numbers in a list does not repeat themselves. Doesn't make sense otherwise.
List1 : 2 2 2
List2 : 2 2
We don't need to iterate all numbers in a list. In worst case we would came across n-1 numbers we have seen before. Like:
list1: 5 6 7
list2: 5 6 7
list3: 5 6 7
So, I would do this;
for list in lists:
max = list[len(list)]
possible_result.append(max)
for j = len(list) to j = len(list)-n in other lists:
max = list[j]
if not max exist in possible_result:
append to possible_result
Find largest possible_result
First iteration would run n times second one, in worst case, n-1 times.

Longest Contiguous Subarray with Average Greater than or Equal to k

Consider an array of N integers. Find the longest contiguous subarray so that the average of its elements is greater (or equal) than a given number k.
The obvious answer has O(n^2) complexity. Can we do better?
We can reduce this problem to longest contiguous subarray with sum >= 0 by subtracting k from all values in O(n) time. Now let's calculate prefix sums:
index 0 1 2 3 4 5 6
array 2 -3 3 2 0 -1
prefix 0 2 -1 2 5 5 4
Now this problem is finding the two indices most far apart with prefix_right - prefix_left >= 0. Let's create a new prefix-index array and sort it by prefix, then indices.
index 2 0 1 3 6 4 5
prefix -1 0 2 2 4 5 5
We can then do a right-to-left sweep to calculate, for each prefix, the maximum index with prefix greater than or equal to the current prefix:
index 2 0 1 3 6 4 5
prefix -1 0 2 2 4 5 5
maxind 6 6 6 6 6 5 5
Now, let's go back to the original prefix array. For each prefix-index pair, we do a binary search on our new array to find the smallest prefix >= the current prefix. We subtract, from maxind of the binary searched prefix, the index of the current prefix to retrieve the best possible sequence length starting at the current index. Take the sequence with the maximum length.
This algorithm is O(n log n) because of the sorting and the n binary searches.
We can solve problem in O(n) time and O(n) space complexity:
I have tried with naive and optimal approach.
In short, the problem involves two steps:
(1) Subtract k from each ar[i] and find cumulative value in new array. Lets call the new array as cumArr[].
(2) Now the problem becomes finding max(j-1) in CumArr[] such that j>i and cumArr[j]>cumArr[i]. This step is a famous question and can be found at lots of places.
Here is the detail with running code:
http://codeshare.io/Y1Xc8
There might be small corner cases which can be handled easily.
Let me know your thoughts friends.

Resources