Day 17 | Grandma Laura and Apples | Lucky Tickets | C++
- Ayush Mahajan
- Sep 4, 2022
- 2 min read

Today we will be solving 2 problems, both have a mathematical approach to the solution0
The key point to note here is that Grandma sold all her apples and we are given instructions about how she sold the apples. So if we start from the end, because we know the value at the end, and run in reverse of what she did, she can get the count of apples she brought to the market.
Let me explain, with sample test case 2
3 10
halfplus
halfplus
halfplusAfter index 2 step, we will reach 0
But she gave away half, so must have reached 0.5
and since it was halved, hence it should be 1 before she sold it
After index 1 step, we will reach 1 (shown above)
But she gave away half, so must have reached 1.5
and since it was halved, hence it should be 3 before she sold it
After the index 0 steps, we will reach 3 (shown above)
But she gave away half, so must have reached 3.5
and since it was halved, hence it should be 7 before she sold it
So basically if apples we halved, then she must have cnt*2 apples earlier, hence grandma will be earning cnt*P
If apples were halfplus, then she must have (cnt*2 + 1) apples earlier, hence grandma will be earning cnt*P + P / 2 (half apple)
This is a fun question.
Few common knowledge points
A number is divisible by 3 if the sum of digits is divisible by 3
If S is sum of digits of X, then S % 3 = X % 3
Using the two above points we can notice that, if we append two numbers A and B, then
append(A,B) % 3 = (A%3 + B%3) % 3
Reason:
append(A,B)%3 = sum of digits of A % 3 + sum of digits of B % 3
Using point 2
append(A,B)%3 = A % 3 + B % 3
Now we know that we have to make append(A, B) % 3 = 0 (modular mathematics)
hence if A % 3 = 0, then B % 3 = 0
A % 3 = 1, then B % 3 = 2
A % 3 = 2, then B % 3 = 1
Thus we can make pair of max(count of elements % 3 = 1, count of elements % 3= 2) + count of element % 3 = 0 / 2
![Day 44 | Binary Search Practice [Leetcode] | C++](https://static.wixstatic.com/media/fbea2a_167f1b66234f4d30b91bcf5b517f83f3~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_167f1b66234f4d30b91bcf5b517f83f3~mv2.jpg)
![Day 43 | Graph and Tree Practice [Leetcode] II | C++](https://static.wixstatic.com/media/fbea2a_361d6f7cd90c431b9f25518e1503da94~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_361d6f7cd90c431b9f25518e1503da94~mv2.jpg)
![Day 42 | Graph Practice [LeetCode] | C++](https://static.wixstatic.com/media/fbea2a_6570bb28577149f19db06704d542789a~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_6570bb28577149f19db06704d542789a~mv2.jpg)
Comments