I'm currently studying algorithms and I was curious about a homework problem (yeah.. I know) that I have been finding conflicting answers on.
In pseudocode the algorithm is:
Algorithm-1(A:array[1..n] of integer) sum,max:integer
sum = 0
max = 0
for i = 1 to n
sum = 0
for j = i to n
sum = sum + A[j]
if sum > max then
max = sum
return max
Given the array, [-1,2,-3,4,-5,6,7,-8,9,-10] I found that the max value that the above function returns should be 4 based on my interpretation of the algorithm, but online the only two answers I've found are 14 and 10.
My understanding of this algorithm is that it takes the base array, finds its sum, and then takes the same array starting at the next index and finds that sum, and the value that's returned is the highest of these sums.
Basically if given the array of [1,2,-3,4,5] it looks at it this way:
Sum of [1,2,-3,4,5] = 9
Sum of [2,-3,4,5] = 8
Sum of [-3,4,5] = 6
Sum of [4,5] = 9
Sum of [5] = 5
And the final max value returned is 9 since 9 > 8 > 6 > 5
Based on this understanding, I'm thinking that the value of my array is 4 from the [6,7,-8,9,-10] sub array. Would that be correct?
Nope, I suppose you are not understanding the concept of subarrays, Subarrays are basically any set of contiguous elements in an array. Let's take your example.
For
[-1,-2,-3,4,-5,6,7,-8,9,-10]
For every array of size N, there are N*(N+1)/2 Subarrays. The answer in this particular case is the subarray [6,7,-8,9] which returns the sum as 14.
Have a look at the below link for better understanding:
Kadane Algorithm for maximum sum subarray
Related
Suppose I have an integer array arr[] with n elements. I've to display the maximum possible sum of n/2 elements. I'm allowed to pick either the leftmost or the rightmost element while traversing to find the sum.
For instance,
arr = 2,100,4,5,6,7,140,1 where n = 8.
So I've to find 4 elements such that their sum is the maximum possible sum and display the sum then.
Possible sets are = {(2,100,4,5),(2,100,4,1),(2,100,140,1),(2,7,140,1),(6,7,140,1)}.
(2,100,140,1) has maximum sum of 243 and hence the expected output.
Another example could be,
arr = 4,5,6,7,8,9 with n = 6.
Thus, n/2 = 3. Expected out 24 (7,8,9).
Can someone help with the logic?
I got a problem about finding the smallest N, where N! contains exactly k trailing zeros.
I've got an idea of finding it through binary search from here - Finding natural numbers having n Trailing Zeroes in Factorial .
Is it possible to calculate it without binary search, using any formula or some iterations?
You can use the formula that the number of times p divides n! is:
k = floor(n/p) + floor(n/p^2) + floor(n/p^3) + ...
Combining this with the fact that the number of trailing zeros is exactly equal to the number of times 5 evenly divides it (each zero corresponds to a 2 and 5 pair, but given 2 is less than 5, we'll always have more 2s than 5s, and thus be constrained by our 5s).
With some algebra, and applying the formula for an infinite geometric series, we can get a very (very!) close lower bound on n. We then just increment n by 5 as much as necessary get the actual result. In practice, this ends up being 1-2 increments for k in the lower thousands, so its fairly negligible.
Full code below:
def count_div5(n):
result = 0
pow5 = 5
while pow5 <= n:
result += n // pow5
pow5 *= 5
return result
def n_from_fact_zeros(k):
n = round(4*k)
n += -n % 5
while count_div5(n) < k:
n += 5
return n
For [1, 2, 3], all possible subsets are {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}
The sum of OR of these subsets are, 1 + 2 + 3 + 3 + 3 + 3 + 3 = 18.
My Approach is to generate all possible subset and find their OR and sum it but time complexity is O(2^n) , but I need a solution with O(nlogn) or less.
As you having 3 alements so 2^3=8 subsets will be created and you need to or all subset and print the sum of all subsets, By following logic you can get the solution you required
public class AndOfSubSetsOfSet {
public static void main(String[] args) {
findSubsets(new int[]{1, 2,3});
}
private static void findSubsets(int array[]) {
int numOfSubsets = 1 << array.length;
int a = 0;
for (int i = 0; i < numOfSubsets; i++) {
int pos = array.length - 1;
int bitmask = i;
int temp = 0;
int count = 0;
while (bitmask > 0) {
if ((bitmask & 1) == 1) {
if (count == 0) {
temp = array[pos];
} else
temp = array[pos] | temp;
count++;
}
//this will shift this number to left so one bit will be remove
bitmask >>= 1;
pos--;
}
count = 0;
a += temp;
temp = 0;
}
System.out.println(a);
}
}
`
one best approach you can use 3 loops outer loop would select number of elements of pair we have to make 2,3,4....upto n. and inner two loops would select elements according to outer loop. in the inner loop you can use bitwise OR so get the answer.
here time complexicity is better than exponential.
if any problem i would gave you code .
please vote if like.
Let's find the solution by calculating bitwise values. Consider the following points first. We will formulate the algorithm based on these points
For N numbers, there can be 2^N-1 such subsets.
For N numbers, where the maximum number of bits can be k, what can be the maximum output? Obviously when every subset sum is all 1's (i.e., for every combination there will be 1 in every bit of k positions). So calculate this MAX. In your example k = 2 and N = 3. So the MAX is when all the subset sum will be 11 (i.e.,3). SO MAX = (2^N-1)*(2^k-1) = 21.
Note that, the value of a bit of subset sum will only be 0 when the bits of every element of that subset is 0. So For every bit first calculate how many subsets can have 0 value in that bit. Then multiply that number with the corresponding value (2^bit_position) and deduct from MAX. In your case, for the leftmost position (i.e., position 0), there is only one 0 (in 2). So in 2^1-1 = 1 subset, the subsets sum's 0 position will be 0. So deduct 1*1 from MAX. Similarly for position 1, there can be only 1 subset with 0 at position 1 of subset sum ({2}). so deduct 1*2 from MAX. For every bit, calculate this value and keep deducting. the final MAX will be the result. If you consider 16 bit integer and you don't know about max k, then calculate using k = 16.
Let's consider another example with N = {1,4}. The subsets are {1},{4},{1,4}, and the result is = 1+4+5 = 10
here k = 3, N = 2. SO MAX = (2^K-1)*(2^N-1) = 21.
For 0 bit, there is only single 0 (in 4). so deduct 1*1 from MAX. So new MAX = 21 -1 = 20.
For 1 bit, both 1 and 4 has 0. so deduct (2^2-1)*2 from MAX. So new MAX = 20 -6 = 14.
For 2 bit, there is only single 0 (in 1). so deduct 1*4 from MAX. So new MAX = 14 -4 = 10.
As we have calculated for every bit position, thus the final result is 10.
Time Complexity
First and second steps can be calculated in constant time
In third step, the main thing is to find the number of 0 bit of each position. So for N number it takes O(k*N) in total. as k will be constant so the overall complexity will be O(N).
I am attempting to solve the below question. I solved this question in O(n^2) time complexity. Is there a way to optimize it further and bring the complexity down to O(n) by iterating the array just once?
Given an array of n integers and a number S. I need to find the minimum set of consecutive integers whose sum is greater than the number S. If no such set exists, I will print 0.
Required complexities:
Space complexity-O(1)
Time Complexity-O(n)
Example-
Array A={2,5,4,6,3,9,2,17,1}
S= 17
Output=2
Explanation-
Possible solutions are:-
{2,5,4,6,3}=2+5+4+6+3=20(>18)=5 numbers
{5,4,6,3,9}=27(>18)=5 numbers
{4,6,3,9}=22(>18)-4 numbers
{6,3,9,2}=20=4 numbers
{3,9,2,17}=4 numbers
{9,2,17}=3 numbers
{2,17}=2 numbers
so, minimum =2 numbers. output=2.
Assuming that all integers are non-negative and S is positive, you can use the following algorithm:
Use two indices, one for where the current sequence starts, and another for where it ends. When the sum of that sequence is too small you extend the sequence by incrementing the second index; if the sum is over S, you keep track of whether it is the best so far and at the same time remove the first value from the sequence, by incrementing the first index.
Here is the algorithm in more formal pseudo code:
n = size(A)
best = n + 1
sum = 0
i = 0
for j = 0 to n - 1:
sum = sum + A[j]
while sum > S:
if j - i + 1 < best:
best = j - i + 1
sum = sum - A[i]
i = i + 1
if best > n:
best = 0
output best
Space complexity is O(1) as there are 4 numerical variables involved (not counting the input array), which represents a fixed amount of memory.
Time complexity is O(n) as the total number of times the statements in the inner loop execute is never more than n (i is incremented each time and will never bypass j).
Given an array A of size N. I need to find the size of the Largest Subset in which any pair of elements within the subset, one of them is divisible by the other.
In short, find largest subset S, where ∀i,j where i ≠ j and i<|S| and j<|S| either Si%Sj=0 or Sj%Si=0.
The bounds for the problem are:
1≤ N≤ 10^3
1≤ Ai≤ 10^9
Sample input/output:
array 4 8 2 3
output is 3
Explanation:
answer set is (4,8,2)
size of the set is 3
I assume there are no duplicates in the array A.
One way to do it (pseudocode, assumes array indices starting at 1):
sort the array A to increasing order
allocate an array B the same length as A
for i in 1 .. N do
B[i] = 1
for j in 1 .. i-1 do
if A[i] % A[j] == 0 then
B[i] = max(B[i], B[j] + 1)
endif
endfor
endfor
return the maximum number in array B as answer.
This runs in O(n2) time and uses O(n) extra space.
It calculates in array B the length of the longest divisor chain consisting of elements of A and ending at the specific element. The overall maximum in B must be the length of the longest such chain.