I have to find the minimum of every row's maximum in matrix. And then print the row which contains that element. Why it cannot be done like this ?
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
if(a[i][j]>max)
max=a[i][j];
}
if(min>max){
min=max;
p=i;
}
}
You need to reset max for each row:
for(i=0; i<m; i++)
{
max = 0; // or some value less than the minimum value in the matrix
for(j=0; j<n; j++)
{
if(a[i][j]>max)
max=a[i][j];
}
if(min>max){
min=max;
p=i;
}
}
Otherwise, once max has replaced min once, a value can never be both greater than max and less than min.
Related
I have this following code. I need to calculate this algorithm complexity but i have no idea where to start. This algorithm has 3 nested loops so i guess its complexity is n^3 or am i wrong?
public static void RadixSort(DataArray data)
{
IList> digits = new List>();
for (int i = 0; i < 10; i++)
{
digits.Add(new List<int>());
}
for (int i = 0; i < data.Length; i++)
{
for (int j = 0; j < data.Length; j++)
{
int digit = (int)((data[j] % Math.Pow(10, i + 1)) / Math.Pow(10, i));
digits[digit].Add((int)data[j]);
}
int index = 0;
for (int k = 0; k < digits.Count; k++)
{
IList<int> selDigit = digits[k];
for (int l = 0; l < selDigit.Count; l++)
{
data.Swap(index++, selDigit[l]);
//data[index++] = selDigit[l];
}
}
for (int k = 0; k < digits.Count; k++)
{
digits[k].Clear();
}
}
}
Calculating complexity is more complex than just look at the number of nested loops. If you have a triple nested loop like this:
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
for(int k=0; k<n; k++)
it will be O(n³), assuming n is not changing in the loop. However, if you consider your case:
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
for(int k=0; k<m; k++)
the time complexity will instead be O(m²n).
And even the simplest sorting algorithms, like bouble sort, selection sort and insertions sort is O(n²), so if your implementation is worse than that you're doing something wrong. The time complexity for radix sort is O(wn), where w is a measure of the size of the elements.
When uncertain about complexity, a reasonable approach is to add counters to the inner-loop code and at the end of the routine print out the counts. Next, vary the size of the input to see how the results change. The empirical results can immediately confirm or deny your analytic or intuited results.
I need to find the maximum sum of non continous subsequence, I have the following code.
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
This works fine, but how do I modify it to exclude the first and the last element from calculation.
Iterate over the array to construct another array with starting element as the ith element and of length n-1 that wraps around the array.
Execute maxSumInSubsequence over each constructed array and find the resultant maximum.
Also, as mentioned in another answer, maxSumInSubsequence could be optimized to have O(n) time complexity.
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
if (n <= 2) return 0;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
public int maxCircularSumInSubsequence(int[] data) {
int n = data.length;
int max = 0;
for (int i = 0; i < n; i++) {
int[] circularData = new int[n-1];
for (int j = 0; j < n - 1; j++) {
circularData[j] = data[(i+j) % n];
}
max = Math.max(maxSumInSubsequence(circularData), max);
}
return max;
}
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl)? incl : excl);
}
Reference : http://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/
The basic logic is to just compute the sum for two possibilities: start i from 0 and then sum up with every alternate array no or start i with i and sum up with every alternate number from there and print the maximum of both.
arr=[5,5,10,100,10,50,1]
def max_sum_suchThatNoTwoElements_are_adjacent(arr,n,su,max_sum):
i=0
while i<n:
su+=arr[i]
if (i+1)<n:
max_sum+=arr[(i+1)]
i+=2
return max(max_sum,su)
print(max_sum_suchThatNoTwoElements_are_adjacent(arr,len(arr),0,0))
My code asks a user to enter an amount of temperatures and prints out the average, then sorts the temperatures in ascending order and descending order. For ascending order I've used selection sort and for descending order I've used bubble sort. My problem is that when I use bubble sort, the last sorted element does not print and I'm not sure why it's doing this. What am I doing wrong?
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("How many temperatures?");
int size=keyboard.nextInt();
int temp[]=new int[size];
System.out.println("Please enter "+temp.length+" temperatures");
double sum=0;
for(int i=0;i<temp.length;i++){
temp[i]=keyboard.nextInt();
sum=sum+temp[i];
}
double average=sum/temp.length;
System.out.println("The average temperature is: "+average);
System.out.println(" ");
System.out.println("Selection sort algorithm for ascending order");
int min;
for (int i = 0; i < temp.length; i++) {
min = i;
for (int j = i + 1; j < temp.length; j++) {
if (temp[j] < temp[min]) {
min = j;
}
}
if (min != i) {
int temporary_var = temp[i];
temp[i] = temp[min];
temp[min] = temporary_var;
}
System.out.print(temp[i]+ " ");
}
System.out.println("");
System.out.println("Bubble sort algorithm for descending order");
for(int i=0; i<temp.length-1; i++)
{
if(temp[i]>temp[i+1])
{
int temporary_var = temp[i ]; //swap elements
temp[i] = temp[ i+1 ];
temp[i+1] = temporary_var;
}
System.out.print(temp[i]+" ");
}
}
}
You are printing in the sorting loop which is for(int i=0; i<temp.length-1; i++) having length-1. That is why it does not print the last element. Change it to for(int i=0; i<temp.length; i++) since you already have a < than operator.
I don't believe Your bubble sort algorithm is correct. Just one loop and swapping? it's just one pass of bubble sort and that won't sort the array for you.
First correct your algorithm and then output the numbers outside loop
Here's the correct code for bubble sort
for(int k=0; k<temp.length; k++)
{
for(int i=0;i<temp.length-1;i++)
{
if(temp[i]>temp[i+1])
{
int temporary_var = temp[i ]; //swap elements
temp[i] = temp[ i+1 ];
temp[i+1] = temporary_var;
}
}
//print array here
Your bubble sort's print statement is part of a for loop that only reaches an index of length minus 2. On zero indexed arrays the last index is length - 1.
Here is the given example:
We have the function which takes one matrix and it's number of columns and it's number of rows and returns int (this is gonna be length). For example:
int function (int** matrix, int n, int m)
The question is what's the fastest algorithm for implementing this function so it returns the maximum length of consecutive fields with the same value (doesn't matter if those same values are in one column or in one row, in this example on picture it's the 5 fields of one column with value 8)?
Values can be from 0-255 (grayscale for example).
So in the given example function should return 5.
If this is a bottleneck and the matrix is large, the first optimization to try is to make one pass over the matrix in sequential memory order (row-by-row in C or C++) rather than two. This is because it's very expensive to traverse a 2d array in the other direction. Cache and paging behavior are the worst possible.
For this you will need a row-sized array to track the number of consecutive values in the current run within each column.
int function (int a[][], int m, int n) {
if (n <= 0 || m <= 0) return 0;
int longest_run_len = 1; // Accumulator for the return value.
int current_col_run_len[n]; // Accumulators for each column
int current_row_run_len = 1; // Accumulator for the current row.
// Initialize the column accumulators and check the first row.
current_col_run_len[0] = 1;
for (int j = 1; j < n; j++) {
current_col_run_len[j] = 1;
if (a[0][j] == a[0][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
}
// Now the rest of the rows...
for (int i = 1; i < m; i++) {
// First column:
if (a[i][0] == a[i-1][0]) {
if (++current_col_run_len[0] > longest_run_len)
longest_run_len = current_col_run_len[0];
} else current_col_run_len[0] = 1;
// Other columns.
current_row_run_len = 1;
for (int j = 1; j < n; j++) {
if (a[i][j] == a[i][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
if (a[i][j] == a[i-1][j]) {
if (++current_col_run_len[j] > longest_run_len)
longest_run_len = current_col_run_len[j];
} else current_col_run_len[j] = 1;
}
}
return longest_run_len;
}
You need to pass over each entry of the matrix at least once, so you can't possible do better than O(m*n).
The most straightforward way is to pass over each row and each column once. This will be two passes over the matrix, but the algorithm is still O(m*n).
Any attempt to do it in one pass will probably be a lot more complex.
int function (int** matrix, int n, int m) {
int best=1;
for (int i=0; i<m; ++i) {
int k=1;
int last=-1;
for (int j=0; j<n; ++j) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
for (int j=0; j<n; ++j) {
int k=1;
int last=-1;
for (int i=0; i<m; ++i) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
return best;
}
I have this problem , where given an array of positive numbers i have to find the maximum sum of elements such that no two adjacent elements are picked. The maximum has to be less than a certain given K. I tried thinking on the lines of the similar problem without the k , but i have failed so far.I have the following dp-ish soln for the latter problem
int sum1,sum2 = 0;
int sum = sum1 = a[0];
for(int i=1; i<n; i++)
{
sum = max(sum2 + a[i], sum1);
sum2 = sum1;
sum1 = sum;
}
Could someone give me tips on how to proceed with my present problem??
The best I can think of off the top of my head is an O(n*K) dp:
int sums[n][K+1] = {{0}};
int i, j;
for(j = a[0]; j <= K; ++j) {
sums[0][j] = a[0];
}
if (a[1] > a[0]) {
for(j = a[0]; j < a[1]; ++j) {
sums[1][j] = a[0];
}
for(j = a[1]; j <= K; ++j) {
sums[1][j] = a[1];
}
} else {
for(j = a[1]; j < a[0]; ++j) {
sums[1][j] = a[1];
}
for(j = a[0]; j <= K; ++j) {
sums[1][j] = a[0];
}
}
for(i = 2; i < n; ++i) {
for(j = 0; j <= K && j < a[i]; ++j) {
sums[i][j] = max(sums[i-1][j],sums[i-2][j]);
}
for(j = a[i]; j <= K; ++j) {
sums[i][j] = max(sums[i-1][j],a[i] + sums[i-2][j-a[i]]);
}
}
sums[i][j] contains the maximal sum of non-adjacent elements of a[0..i] not exceeding j. The solution is then sums[n-1][K] at the end.
Make a copy (A2) of the original array (A1).
Find largest value in array (A2).
Extract all values before the it's preceeding neighbour and the values after it's next neighbour into a new array (A3).
Find largest value in the new array (A3).
Check if sum is larger that k. If sum passes the check you are done.
If not you will need to go back to the copied array (A2), remove the second larges value (found in step 3) and start over with step 3.
Once there are no combinations of numbers that can be used with the largest number (i.e. number found in step 1 + any other number in array is larger than k) you remove it from the original array (A1) and start over with step 0.
If for some reason there are no valid combinations (e.g. array is only three numbers or no combination of numbers are lower than k) then throw an exception or you return null if that seems more appropriate.
First idea: Brute force
Iterate all legal combination of indexes and build the sum on the fly.
Stop with one sequence when you get over K.
keep the sequence until you find a larger one, that is still smaller then K
Second idea: maybe one can force this into a divide and conquer thing ...
Here is a solution to the problem without the "k" constraint which you set out to do as the first step: https://stackoverflow.com/a/13022021/1110808
The above solution can in my view be easily extended to have the k constraint by simply amending the if condition in the following for loop to include the constraint: possibleMax < k
// Subproblem solutions, DP
for (int i = start; i <= end; i++) {
int possibleMaxSub1 = maxSum(a, i + 2, end);
int possibleMaxSub2 = maxSum(a, start, i - 2);
int possibleMax = possibleMaxSub1 + possibleMaxSub2 + a[i];
/*
if (possibleMax > maxSum) {
maxSum = possibleMax;
}
*/
if (possibleMax > maxSum && possibleMax < k) {
maxSum = possibleMax;
}
}
As posted in the original link, this approach can be improved by adding memorization so that solutions to repeating sub problems are not recomputed. Or can be improved by using a bottom up dynamic programming approach (current approach is a recursive top down approach)
You can refer to a bottom up approach here: https://stackoverflow.com/a/4487594/1110808