Reach a Number | Live Coding with Explanation | Leetcode #754

preview_player
Показать описание
To support us you can donate

Check out our other popular playlists:

If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful.

#coding #leetcode #programminglife #programmingisfun #programmer #tech #software #codinglife #leetcode
Комментарии
Автор

We hope you all are enjoying our videos!!! Don't forget to leave a comment!!! Please like the video to support us!!!

Questions you might like:

Struggling in a question??

Leave in a comment and we will make a video!!!🙂🙂🙂

AlgorithmsMadeEasy
Автор

I like to add more observation that every step has capacity to reduce 2n steps, where n is step count.
let x = (sum - target)/2.
Then if we take x step in backward direction, we are at the target.

vineetkumar
Автор

It's better to explain the intuition instead of simply just telling the algorithm

NANUVALAADITHYA
Автор

Don't we need to ensure k in 2*k is less than step(k<steps). As we can only do this flipping if k < less than step. If we never reached the step we cant negate it.
For example number 42. The progression would be
step1: add 1-> 1
step2: add 2-> 3
step3: add 3-> 6
step4: add 4-> 10
step5: add 5-> 15
step6: add 6-> 21
step7: add 7-> 28
step8: add 8-> 36
step9: add 9-> 45(45-42 is odd)
step10: add 10-> 55(55-42 is odd)
step11: add 11-> 66(66-42=2*12).
=> k=12 or (1+ 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 - 2*12 = 42 )
you need to flip the 12th step in a total of 11 steps?

sangameshkodge
Автор

GUYS MY CODE CAN HANDLE ALL NUMBERS
import java.util.Scanner;
public class Main {
public static int reachTarget(int target) {
if (target < 0)
return target * -1 * 2;
else {
int sum = 1;
int moves = 1;
while (sum < target) {
moves++;
sum += moves;
}
if(sum>target){
sum-=moves;
return (moves-1 + (target-sum)*2);}
else{
return moves;
}
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the target: ");
int target = sc.nextInt();
System.out.print("The number of moves are: " + reachTarget(target));
}
}

mr.computer
Автор

Do a dry run of example different from the example given in the question. It would help better.

AnkitKumar-mbvl
Автор

I tried solving using bfs but it gives TLE
class Solution {
public:
int reachNumber(int target) {
queue<int>q;
q.push(0);
int steps=1;

while(!q.empty()){
int n = q.size();

for(int i=0; i<n; i++){
int curr = q.front();
q.pop();

if(curr==target) return steps-1;
//push 2 choices
q.push(curr + steps);
q.push(curr - steps);
}

steps++;

}
return steps-1;
}
};

aayush
Автор

in case when target ==
2 why we are going to -1

adityaparihar
join shbcf.ru