I want to delete some ListViewSubItem if they are checked. I want to remove them from the ListView and from a list (List Products) by the sku.
I´m getting an ArgumentOutOfRangeException if I add 1 to the ListViewSubItem´s index and if I dont´t, I can´t delete the first subitem. Pl hlp.
Thanks.
My code:
int count = lv_list.Items.Count;
for (int j = count - 1; j >= 0; j--)
if (lv_list.Items[j].Checked)
{
sku = lv_list.Items[j].SubItems[j+1].Text;
lv_list.Items[j].Remove();
DeleteProductBySKU(sku);
}
As pointed out via comments, j+1 is a wrong index for SubItems. What you know for sure is that j is a valid index for Items, but don't have any information about the corresponding SubItems (if j+1 or even j are valid). A quick fix avoiding errors:
for (int j = count - 1; j >= 0; j--)
if (lv_list.Items[j].Checked)
{
if (lv_list.Items[j].SubItems.Count - 1 >= j + 1) //lv_list.Items[j].SubItems.Count - 1 -> last index of SubItems
{
sku = lv_list.Items[j].SubItems[j + 1].Text;
}
else
{
sku = lv_list.Items[j].SubItems[lv_list.Items[j].SubItems.Count - 1].Text;
//sku = lv_list.Items[j].SubItems[0].Text -> to choose the first SubItem
}
lv_list.Items[j].Remove();
DeleteProductBySKU(sku);
}
The code above takes the last SubItem in case that j+1 is not a valid index. It avoids errors but I guess that this is not what you are looking for. You should update the code to modify the SubItem you really want (which should either be a constant value or defined by another counter different than j).
Related
This is the Dynamic Programming algorithm.
int bin2(int n, int k){
index i, j;
i tn B[0 ][0 k] B[0..n][0..k]; i
for(i=0; i <= n; i++)
for(j=0; j <= minimum(i,k); j++)
if (j 0 || j i) [i][j] 1
i
if (j==0 || j==i) B[i][j] = 1;
else B[i][j] = B[i-1][j-1] + B[i-1][j];
return B[n][k];
}
Its spatial complexity is O(n^2).
Can this be lowered to O(n)?
What should I do if I can use the property that 'when the calculation of a row is finished, the previously calculated value is not needed'?
In the code above, I got a hint that you can change k to 1 and j to j%2. What should I do?
The key is this line
B[i][j] = B[i-1][j-1] + B[i-1][j];
You see that, for the current state, we are dependent on i-1 and j-1. We don't need all of the previous rows, just the i-1th row.
Method 1
You should be looking to change it to something like
B[j] += B[j - 1];
Keep overwriting the same 1D array i.e iterating over j for each i.
Try solving it by yourself. If you still want to look at the solution, it is at the end of my answer.
Method 2
Some people like to keep two rows one for earlier and one for current one. They alternate between 0th row and 1st row by using mod. (i+1) % 2 will give 1 when i = 0 and 0 when i = 1. But this method uses two arrays instead of one as shown in method one.
Method 3
Similar to method 2. Some people keep two arrays previous and current. They swap the whole array instead of changing which array is the current one to fill. The swap happens after the j loop and inside the i loop. Refer the solution by #Maurycyt for this method.
Efficiency wise: Method 1 > Method 2 > Method 3
Solution with Method 1:
int binomialCoeff(int n, int k)
{
vector<int> dp(k+1, 0);
dp[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = min(i, k); j > 0; j--)
dp[j] += dp[j-1];
}
return dp[k];
}
I am confused with your code, which seems to have several typos, but here is how you can evaluate {n \choose k} in linear spatial complexity, using the fact that {n \choose k} = (n!)/(k!*(n-k)!) is the k-th element of the n-th row of Pascal's triangle (which you seem to already know, I am just making sure it's out here).
int nchoosek(int n, int k)
{
int i, j; //These are indices of the row and column respectively
int oldrow [n+1], newrow [n+1]; //n+1 is the largest size of a row we will need.
//we will be computing a row of Pascal's triangle based on the previous row,
//then swapping the two.
for (i = 0; i <= n; i++) //we iterate over the rows
{
for (j = 0; j <= i; j++) //we iterate over the elements in a row, there are i+1 elements in row i, thus n+1 elements in row n.
{
if (j == 0 || j == i)
newrow[j] = 1; //we set the first and last element of a row to 1.
else
newrow[j] = oldrow[j-1] + oldrow[j]; //we set the other elements to the sum of the two elements above them in Pascal's triangle.
}
swap(oldrow, newrow); //we swap the two arrays, and will now be counting the next row, using the row which we just counted.
}
//the i-th row of Pascal's triangle will always end up in the oldrow array
return oldrow[k]; //we return its k-th element.
}
Given a n*m matrix, a cell is called good cell if row number (i) divides column number (j)
Example :
2*3 matrix => cells are {1,1}, {1,2}, {1,3}, {2,1}, {2,2}, {2,3} from which good cells can be defined as {1,1}, {1,2}, {1,3}, {2,2}
So the output is 4
I have figure out the logic for this, row 1 has all cells as good cells, row 2 has m/2 good cells, row 3 has m/3 good cells. (I am using just the integer dividend)
m/1 + m/2 + m/3 + ........ + m/n;
For which my code looks like =>
long count=1;
long answer = 0;
while(count<=n){
answer=answer + m/count;
count++;
}
But this code is getting timed out when I am submitting my solution. Need help to find better approach for this.
PS: Coding challenge is already over.
Try this one,
for(int i = 0 ; i < n; i++)
{
for(int j = 0; j < m; j += i) // j += i will save unwanted loops
{
// rest of your logic
}
}
As the value of i gets higher and higher nested loop will become more efficient
edit
The below code will be more efficient & correct than above. Now nested loop starts with the value of i instead of 0
for(int i = 0 ; i < n; i++)
{
for(int j = i; j < m; j += i) //j = i & j += i will save unwanted loops
{
// rest of your logic
}
}
as noted by n pronouns m this post incorrect since it only considers the case n==m
You may have a look at the Dirichlet divisor problem
One attempt is the formula of Benoit Cloitre:
(below octave implem)
function s = sumit(n)
s = 0;
for i = 1:n
s += floor(n/i);
end
end
n = 1e6
expect = sumit(n)
%A006218
u = floor(sqrt(n));
res = 2*sum(floor(n./(1:u))) - u^2
Where you avoid summing quite some terms.
Link: https://leetcode.com/problems/first-bad-version/discuss/71386/An-clear-way-to-use-binary-search
I am doing a question wherein, given a string like this "FFTTTT", I have to find either the rightmost F or the leftmost T.
The following is the code:
To find the leftmost T
public int firstBadVersionLeft(int n) {
int i = 1;
int j = n;
while (i < j) {
int mid = i + (j - i) / 2;
if (isBadVersion(mid)) {
j = mid;
} else {
i = mid + 1;
}
}
return i;
}
I have the following doubts:
I am unable to understand the intuition behind returning i. I mean, why didn't we return j. I did a trial run of the code in my mind, and it works out, but how do we know we have to return i.
Why didn't we do while (i<=j) and just while(i<j). I mean, how do we determine this?
You stop when i==j as far as I can tell. So you can return either of them since they have the same value.
The difference between the two conditions is i == j . In that case mid == i + 0/2 == i. So isBadVersion can return true or false. If it returns true then you do j= mid, but we already had i == j == mid, so you don't do anything and you have an infinite loop. If isBadVersion returns false then you will make i == j+1 and the loop will end. Since the boundaries are inclusive (they include the i'th and j'th element) this can only happen if there's no 'T' in the string.
So you do (i < j) to avoid that infinite loop case.
P.S. This code will return n if there's not 'T' in the string or the last character is a 'T'. Not sure if that's intended or not.
I have to sort this array in O(n) time and O(1) space.
I know how to sort an array in O(n) but that doesn't work with missing and repeated numbers. If I find the repeated and missing numbers first (It can be done in O(n)) and then sort , that seems costly.
static void sort(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
if(i>=arr.length)
break;
if(arr[i]-1 == i)
continue;
else
{
while(arr[i]-1 != i)
{
int temp = arr[arr[i]-1];
arr[arr[i]-1] = arr[i];
arr[i] = temp;
}
}
}
}
First, you need to find missing and repeated numbers. You do this by solving following system of equations:
Left sums are computed simultaneously by making one pass over array. Right sums are even simpler -- you may use formulas for arithmetic progression to avoid looping. So, now you have system of two equations with two unknowns: missing number m and repeated number r. Solve it.
Next, you "sort" array by filling it with numbers 1 to n left to right, omitting m and duplicating r. Thus, overall algorithm requires only two passes over array.
void sort() {
for (int i = 1; i <= N; ++i) {
while (a[i] != a[a[i]]) {
std::swap(a[i], a[a[i]]);
}
}
for (int i = 1; i <= N; ++i) {
if (a[i] == i) continue;
for (int j = a[i] - 1; j >= i; --j) a[j] = j + 1;
for (int j = a[i] + 1; j <= i; ++j) a[j] = j - 1;
break;
}
}
Explanation:
Let's denote m the missing number and d the duplicated number
Please note in the while loop, the break condition is a[i] != a[a[i]] which covers both a[i] == i and a[i] is a duplicate.
After the first for, every non-duplicate number i is encountered 1-2 time and moved into the i-th position of the array at most 1 time.
The first-found number d is moved to d-th position, at most 1 time
The second d is moved around at most N-1 times and ends up in m-th position because every other i-th slot is occupied by number i
The second outer for locate the first i where a[i] != i. The only i satisfies that is i = m
The 2 inner fors handle 2 cases where m < d and m > d respectively
Full implementation at http://ideone.com/VDuLka
After
int temp = arr[arr[i]-1];
add a check for duplicate in the loop:
if((temp-1) == i){ // found duplicate
...
} else {
arr[arr[i]-1] = arr[i];
arr[i] = temp;
}
See if you can figure out the rest of the code.
I was wondering how could I get the longest positive-sum subsequence in a sequence:
For example I have -6 3 -4 4 -5, so the longest positive subsequence is 3 -4 4. In fact the sum is positive (3), and we couldn't add -6 neither -5 or it would have become negative.
It could be easily solvable in O(N^2), I think could exist something much more faster, like in O(NlogN)
Do you have any idea?
EDIT: the order must be preserved, and you can skip any number from the substring
EDIT2: I'm sorry if I caused confusion using the term "sebsequence", as #beaker pointed out I meant substring
O(n) space and time solution, will start with the code (sorry, Java ;-) and try to explain it later:
public static int[] longestSubarray(int[] inp) {
// array containing prefix sums up to a certain index i
int[] p = new int[inp.length];
p[0] = inp[0];
for (int i = 1; i < inp.length; i++) {
p[i] = p[i - 1] + inp[i];
}
// array Q from the description below
int[] q = new int[inp.length];
q[inp.length - 1] = p[inp.length - 1];
for (int i = inp.length - 2; i >= 0; i--) {
q[i] = Math.max(q[i + 1], p[i]);
}
int a = 0;
int b = 0;
int maxLen = 0;
int curr;
int[] res = new int[] {-1,-1};
while (b < inp.length) {
curr = a > 0 ? q[b] - p[a-1] : q[b];
if (curr >= 0) {
if(b-a > maxLen) {
maxLen = b-a;
res = new int[] {a,b};
}
b++;
} else {
a++;
}
}
return res;
}
we are operating on input array A of size n
Let's define array P as the array containing the prefix sum until index i so P[i] = sum(0,i) where `i = 0,1,...,n-1'
let's notice that if u < v and P[u] <= P[v] then u will never be our ending point
because of the above we can define an array Q which has Q[n-1] = P[n-1] and Q[i] = max(P[i], Q[i+1])
now let's consider M_{a,b} which shows us the maximum sum subarray starting at a and ending at b or beyond. We know that M_{0,b} = Q[b] and that M_{a,b} = Q[b] - P[a-1]
with the above information we can now initialise our a, b = 0 and start moving them. If the current value of M is bigger or equal to 0 then we know we will find (or already found) a subarray with sum >= 0, we then just need to compare b-a with the previously found length. Otherwise there's no subarray that starts at a and adheres to our constraints so we need to increment a.
Let's make a naive implementation and then improve it.
We move from the left to the right calculating partial sums and for each position we find the most-left partial sum such as the current partial sum is greater than that.
input a
int partialSums[len(a)]
for i in range(len(a)):
partialSums[i] = (i == 0 ? 0 : partialSums[i - 1]) + a[i]
if partialSums[i] > 0:
answer = max(answer, i + 1)
else:
for j in range(i):
if partialSums[i] - partialSums[j] > 0:
answer = max(answer, i - j)
break
This is O(n2). Now the part of finding the left-most "good" sum could be actually maintained via BST, where each node would be represented as a pair (partial sum, index) with a comparison by partial sum. Also each node should support a special field min that would be the minimum of indices in this subtree.
Now instead of the straightforward search of an appropriate partial sum we could descend the BST using the current partial sum as a key following the next three rules (assuming C is the current node, L and R are the roots of the left and the right subtrees respectively):
Maintain the current minimal index of "good" partial sums found in curMin, initially +∞.
If C.partial_sum is "good" then update curMin with C.index.
If we go to R then update curMin with L.min.
And then update the answer with i - curMin, also add the current partial sum to the BST.
That would give us O(n * log n).
We can easily have a O(n log n) solution for longest subsequence.
First, sort the array, remember their indexes.
Pick all the largest numbers, stop when their sum are negative, and you have your answer.
Recover their original order.
Pseudo code
sort(data);
int length = 0;
long sum = 0;
boolean[] result = new boolean[n];
for(int i = n ; i >= 1; i--){
if(sum + data[i] <= 0)
break;
sum += data[i];
result[data[i].index] = true;
length++;
}
for(int i = 1; i <= n; i++)
if(result[i])
print i;
So, rather than waiting, I will propose a O(n log n) solution for longest positive substring.
First, we create an array prefix which is the prefix sum of the array.
Second, we using binary search to look for the longest length that has positive sum
Pseudocode
int[]prefix = new int[n];
for(int i = 1; i <= n; i++)
prefix[i] = data[i];
if(i - 1 >= 1)
prefix[i] += prefix[i - 1];
int min = 0;
int max = n;
int result = 0;
while(min <= max){
int mid = (min + max)/2;
boolean ok = false;
for(int i = 1; i <= n; i++){
if(i > mid && pre[i] - pre[i - mid] > 0){//How we can find sum of segment with mid length, and end at index i
ok = true;
break;
}
}
if(ok){
result = max(result, mid)
min = mid + 1;
}else{
max = mid - 1;
}
}
Ok, so the above algorithm is wrong, as pointed out by piotrekg2 what we need to do is
create an array prefix which is the prefix sum of the array.
Sort the prefix array, and we need to remember the index of the prefix array.
Iterate through the prefix array, storing the minimum index we meet so far, the maximum different between the index is the answer.
Note: when we comparing value in prefix, if two indexes have equivalent values, so which has smaller index will be considered larger, this will avoid the case when the sum is 0.
Pseudo code:
class Node{
int val, index;
}
Node[]prefix = new Node[n];
for(int i = 1; i <= n; i++)
prefix[i] = new Node(data[i],i);
if(i - 1 >= 1)
prefix[i].val += prefix[i - 1].val;
sort(prefix);
int min = prefix[1].index;
int result = 0;
for(int i = 2; i <= n; i ++)
if(prefix[i].index > min)
result = max(prefix[i].index - min + 1, result)
min = min(min, prefix[i].index);