# Apple and Orange in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank, Algorithm Solutions of Problem Solving Section in Java. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Apple and Orange in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

`Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.`

#### Introduction To Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results.

• It is easy to understand.
• Algorithm is a step-wise representation of a solution to a given problem.
• In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Link for the ProblemApple and Orange – Hacker Rank Solution

`Apple and Orange – Hacker Rank Solution`

### Problem:

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam’s house.

In the diagram below:

• The red region denotes the house, where  is the start point, and  is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right.
• Assume the trees are located on a single point, where the apple tree is at point , and the orange tree is at point .
• When a fruit falls from its tree, it lands  units of distance from its tree of origin along the -axis. *A negative value of  means the fruit fell  units to the tree’s left, and a positive value of  means it falls  units to the tree’s right. *
```1
2
```

Function Description

Complete the countApplesAndOranges function in the editor below. It should print the number of apples and oranges that land on Sam’s house, each on a separate line.

countApplesAndOranges has the following parameter(s):

• s: integer, starting point of Sam’s house location.
• t: integer, ending location of Sam’s house location.
• a: integer, location of the Apple tree.
• b: integer, location of the Orange tree.
• apples: integer array, distances at which each apple falls from the tree.
• oranges: integer array, distances at which each orange falls from the tree.

Input Format

The first line contains two space-separated integers denoting the respective values of  and .
The second line contains two space-separated integers denoting the respective values of  and .
The third line contains two space-separated integers denoting the respective values of  and .
The fourth line contains  space-separated integers denoting the respective distances that each apple falls from point .
The fifth line contains  space-separated integers denoting the respective distances that each orange falls from point .

Constraints

Output Format

Print two integers on two different lines:

1. The first integer: the number of apples that fall on Sam’s house.
2. The second integer: the number of oranges that fall on Sam’s house.

Sample Input 0

```7 11
5 15
3 2
-2 2 1
5 -6
```

Sample Output 0

```1
1
```

Explanation 0

`Apple and Orange – Hacker Rank Solution`
```import java.util.Scanner;

/**
* @author Techno-RJ
*
*/
public class AppleAndOrange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int t = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int m = sc.nextInt();
int n = sc.nextInt();
int aCount = 0, oCount = 0;
for (int i = 0; i < m; i++) {
int temp = sc.nextInt();
if ((a + temp) >= s && (a + temp) <= t) {
aCount++;
}
}

for (int i = 0; i < n; i++) {
int temp = sc.nextInt();
if ((b + temp) >= s && (b + temp) <= t) {
oCount++;
}
}
System.out.println(aCount);
System.out.println(oCount);
sc.close();
}
}```

### 444 thoughts on “Apple and Orange in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]”

1. where to buy spironolactone without a prescription oral aldactone 25mg order valacyclovir 500mg without prescription

2. purchase provigil without prescription provigil pills prednisone 10mg without prescription

3. After exploring a handful of the blog posts on your website, I really appreciate your technique of blogging.
I book-marked it to my bookmark webpage list and will be checking back in the
near future. Please check out my website as well and let me know how you feel.

4. Thread Rating: His goal was to sell merch for the most popular Youtube creators. It was a hard goal given he didn’t have much traction. Twitter “I’ve been pretty active with the slot influencer community since early 2016. I am in full support of anything that increases the popularity and reach of casino gaming, and slot-playing videos being posted on YouTube or live-streamed certainly do that.” With all the angst over declining slot play and millennials allegedly turning away from gambling, casino managers could not have created a better marketing platform than slot YouTubers if they had tried. Alex Millson, Bloomberg News Find out which slot and casino YouTube channels are the most popular right now. With so many slot channels, what makes one more popular than the other? Being photogenic certainly doesn’t hurt, but being interesting and relatable is probably more important. Judging by the comments, most viewers like playing slots themselves and enjoy watching people like them win money. People like seeing big jackpots, so that means playing high limit machines that, over time, take considerably more than they give back to players. Filming your slot play and monetizing it might, at worst, be a way to defray an expensive hobby.
https://weekly-wiki.win/index.php?title=Betway_slot_games
On this review web page, we have listed the top-rated online bingo sites you can find the popular slot game. Fluffy Too is the best slot game for UK players as it has amazing features, including bonus offers. That’s not all. The operators on our page are regulated by well-known commissions. So, you can be sure of fair and secure gameplay here. Apart from the traditional game features, there is also a Fluffy Too jackpot game. But always remember that online gambling is a game of chance. So, if the ‘lady luck’ is in your corner, you may walk away with a huge cash prize reward. From Death, Comes Life is the second challenge on Day 2 of the Tales of the Fantastic Event. Target the Illumination Dragonfish the most to make it self-destruct!

https://copyhara.com/bbs/board.php?bo_table=free&wr_id=103553

6. 25 mg, 50 mg, 100 mg Die Lösung ist größer als das Problem Aber lassen Sie sich nicht vom weniger aufregenden Äußeren täuschen. Sildenafil oder generisches Viagra gibt es in den gleichen Dosierungen wie Viagra und wirkt genauso. Der entscheidende Unterschied ist der Preis: Viagra kostet mehr als Sildenafil, weil es ein Markenname ist. Die Lösung ist größer als das Problem PhysiotherapieErgotherapieBetriebliche Gesundheit (BGM)TrainingKurse & WeiterbildungMassage Hinweis: Im Interesse einer besseren Lesbarkeit wird bei Personenbezeichnungen und personenbezogenen Hauptwörtern auf dieser Website die männliche Form verwendet. Entsprechende Begriffe gelten im Sinne der Gleichbehandlung und uneingeschränlt für alle weiteren Geschlechter. Die verkürzte Sprachform beinhaltet keine Wertung.
http://www.bjmetal.co.kr/bbs/board.php?bo_table=free&wr_id=9470
20 pillen, 30 pillen, 60 pillen, 90 pillen, 120 pillen Anmelden Abmelden Priligy (Wirkstoff: Dapoxetin) ist das erste Arzneimittel zur Behandlung von vorzeitiger Ejakulation (ejaculatio praecox) oder vorzeitigem Orgasmus. Im Gegensatz zu Erektionsstörungen ist der vorzeitige Samenerguss ein Problem, das in allen Alterskategorien vorkommt. Anmelden Abmelden Weiterführende Links „Hi Five Music Award“ Weiterführende Links „Hi Five Music Award“ Veröffentlicht am 07. Dez 2021 um 05:46 Uhr unter News Weiterführende Links „Hi Five Music Award“ Priligy (Wirkstoff: Dapoxetin) ist das erste Arzneimittel zur Behandlung von vorzeitiger Ejakulation (ejaculatio praecox) oder vorzeitigem Orgasmus. Im Gegensatz zu Erektionsstörungen ist der vorzeitige Samenerguss ein Problem, das in allen Alterskategorien vorkommt.

7. Loved your idea! Very creative.

8. Is the author still keeping up with the blog? I’m craving more content about this topic!

9. Your article is excellent! The information is presented clearly, and I’m curious if you plan to add more images in your upcoming pieces. It could enhance the overall reader experience.

11. I every time emailed this web site post page to all my contacts, since
if like to read it then my contacts will too.

12. Hi there! I just wanted to ask if you ever have
any problems with hackers? My last blog (wordpress) was hacked and I ended
up losing many months of hard work due to no data backup.
Do you have any methods to stop hackers?

13. С тех пор, как я решил перейти на здоровое питание, моя жизнь кардинально изменилась. На моей кухне появилась соковыжималка ручная от компании ‘Все соки’. С её помощью я начал каждое утро с свежевыжатого сока, что несказанно радует меня. Спасибо, ‘Все соки’! https://h-100.ru/collection/ruchnye-shnekovye-sokovyzhimalki – Соковыжималка ручная – лучшее, что со мной случилось!

14. reggionotizie.com
게다가 이들 대부분은 저속한 사람들이고 그들 중 누구도 괜찮은 사람이 아닙니다.

15. saungsantoso.com
그 Xu Jing은 Ningbo에 도착했으며 곧 Tianjin과 수도에 도착할 것입니다.

https://cashgogy319483.newsbloger.com/25266101/eu-casino-mobile
ESRB ratings provide information about what’s in a game or app so parents and consumers can make informed choices about which games are right for their family. Ratings have 3 parts: Rating Categories, Content Descriptors, and Interactive Elements. Other: With new bin containers and mapping, you can organize and group content any way you want. Preview PhraseFind AI and ScriptSync AI, the new and improved AI-powered versions of these extremely popular timesaving features that help you find footage in seconds, searching for clips and takes based on the dialog they contain.   For a video ad to serve: Collecting data has never been easier. Video forms let you collect valuable contact details and feedback in an engaging, interactive, and personal way.

17. saungsantoso.com
“읽지 않아도 된다.” 많은 일본인들은 “지금 사겠습니다”라고 신이 났습니다.

18. Metal scraps recovery Scrap aluminium sorting and grading Aluminium scrap grade analysis
Metal scrap yard solutions, Aluminum cable scrap transportation logistics, Metal waste disassembling

19. Metal recovery and repurposing Aluminium scrap market analysis Scrap aluminium export
Scrap metal sourcing solutions, Buying aluminum cable scrap, Scrap metal reclaiming operations

20. 🌌 Wow, this blog is like a fantastic adventure soaring into the universe of wonder! 💫 The captivating content here is a captivating for the imagination, sparking awe at every turn. 🌟 Whether it’s lifestyle, this blog is a goldmine of exciting insights! #InfinitePossibilities Embark into this exciting adventure of discovery and let your imagination roam! 🚀 Don’t just read, savor the thrill! #BeyondTheOrdinary Your brain will thank you for this exciting journey through the dimensions of discovery! 🌍

21. To boost accessibility to its DeFi services, Uniswap (UNI) has deployed its V3 network on Rootstock, a Bitcoin sidechain. GFX Labs, the same team responsible for the Oku trading terminal, completed the deployment. As stated in a Network Upgrade Specification document, the following changes to the Bitcoin Cash network would activate in the May 15 upgrade: CHIP-2021-01 Restrict Transaction Version, CHIP-2021-01 Minimum Transaction Size, CHIP-2022-02 CashTokens and CHIP-2022-05 P2SH32. — While Bitcoin Cash and Bitcoin share a number of technical similarities, such as a maximum token supply of 21 million coins and a proof-of- (PoW) consensus method, Bitcoin Cash is designed to facilitate fast peer-to-peer (P2P) payments between users. For this reason, Bitcoin Cash prices are steady yet weak, dropping 5% in the past month as the coin trades at \$110.95.
https://www.coincarp.com/currencies/allextoken/socials/

22. digiyumi.com
하지만 … Liu Wenshan에 비해 그는 정말 창백합니다.

23. This post was a breath of fresh air. Thank you for your unique insights!

25. 💫 Wow, this blog is like a cosmic journey blasting off into the universe of wonder! 🎢 The captivating content here is a thrilling for the mind, sparking curiosity at every turn. 🌟 Whether it’s lifestyle, this blog is a treasure trove of exhilarating insights! 🌟 🚀 into this thrilling experience of knowledge and let your mind roam! ✨ Don’t just enjoy, immerse yourself in the excitement! 🌈 Your brain will be grateful for this exciting journey through the dimensions of discovery! 🚀

26. This was a great read—thought-provoking and informative. Thank you!

27. Your writing style is captivating! I was engaged from start to finish.

28. Thank you for consistently producing such high-quality content.

29. Thank you for consistently producing such high-quality content.

30. Your piece was both informative and thought-provoking. Thanks for the great work!

31. Thank you for adding value to the conversation with your insights.

32. binsunvipp.com
Hongzhi 황제는 그의 아버지가 그의 아들만큼 좋지 않다고 느끼며 마음 속으로 감정을 느꼈습니다.

34. Metal scrap supply chain Metal scraps buyback Iron scrap disassembly

Ferrous material bulk handling, Iron scrap collection services, Metal residue

35. strelkaproject.com
Fang Jifan은 “잊어라. 이 행복한 이벤트를 듣고 싶지 않다”고 비웃었다.

36. pragmatic-ko.com
그러므로 편안함은 사랑스러운 독자들에게, 외로움과 서늘함은 나 자신에게 맡겨진다.

37. smcasino7.com
Zhu Houzhao는 “하지만 지금은…아직 할 일이 많습니다.”라고 말했습니다.

38. Your writing style is both engaging and informative. We’re proud to support your blog from Asheville!

39. Your writing is like a beacon of light in the darkness, guiding us towards knowledge and understanding. Asheville appreciates your blog!

40. pragmatic-ko.com
Liu Jian과 Li Dongyang은 여전히 상황을 인식하지 못하고 신중하게 둘러 보았습니다.

41. sm-casino1.com
이 정직하고 충성스러운 Ouyang Zhi가 그런 부적절한 말을 하는 것은 당연합니다.

42. lfchungary.com
Fang Jifan이 가장 싫어하는 것은 누군가 그에게 돈을 요구하고 그는 매우 가난하다는 것입니다.

43. lfchungary.com
“계속 돈과 물건은 똑같고 아무 상관이 없다고 말하는 당신이오?”

44. smcasino7.com
Fang Jifan의 청순한 얼굴이 나와 관련이 있습니까? 좋은 일과 나쁜 일에 대해 책임을 져야 합니까?

45. andrejpos.com
명나라 현종에서 홍지나라에 이르기까지 조정 간의 분쟁은 끊이지 않았다.

46. lfchungary.com
상인들이 물고기를 팔아 많은 돈을 벌고 있는 것을 보고, 어찌 서둘러서 장사를 하지 않을 수 있겠습니까?

47. Metal waste pricing Ferrous metal processing Iron resource recovery

Ferrous material recycling partnership, Iron waste management, Metal waste storage

48. sm-slot.com
Hongzhi 황제는 “Fang Jifan은 매우 슬플 것입니다. “라고 고개를 끄덕였습니다.

49. Metal waste compacting Ferrous scrap analytics Iron recycling and recovery

Ferrous material recycling productivity, Iron scrap inventory services, Metal scrap trading

50. laanabasis.com
그리고 그들이 추천한 관료가 적지 않은데 모두 홍치제를 잘 아는 사람들이다.

51. chutneyb.com
내각에 들어갈 수있는 Zhongshusheren과 서기관은 모두 훌륭한 사람들입니다.

52. mega-casino77.com
Zhu Houzhao는 미소를 지으며 Fang Jifan을 바라보며 매우 흥분했습니다.

53. Scrap metal ecological impact Ferrous material customer service Iron scrap brokerage and trading

Ferrous metal recycling industry, Iron scrap repurposing center, Metal reclamation and recovery yard

그의 전신은 마치 무한한 힘으로 가득 차 있는 것처럼 놀랍게 보였다.

55. strelkaproject.com
Fang Jifan이 들어 와서 Hongzhi 황제를 보았을 때 그는 앞으로 나아가고 싶은 것처럼 보였습니다.

56. smcasino-game.com
새해를 맞아 문화역사박물관에서 근무 중인 한린은 기분이 이상하다.

57. ttbslot.com
Concubine Fang은 주저하고 천천히 병 뚜껑을 들어 올렸고 이상한 향기가 그녀의 마음에 곧바로 돌진했습니다.

58. qiyezp.com
그러나 Fang Jifan은 석탄 채굴에서 유통까지 시작하고 싶다면 처음에는 모든 것이 어렵다는 것을 알고 있었습니다.

59. sandyterrace.com
Zhu Houzhao는 신나게 춤을 추고 특별한 높은 플랫폼으로 뛰어 올랐습니다.

60. ihrfuehrerschein.com
Zhao Yi의 얼굴은 붉어졌지만 고개를 들었을 때 친숙한 표정으로 Hongzhi 황제를 보았습니다.

61. donmhomes.com
素敵な記事をありがとうございます。心から感謝しています。

62. bmipas.com
知識が豊富で読みやすい素晴らしい記事でした。

63. Looking for anonymity in your Ethereum transactions? Check out TornadoCash, the leading solution for privacy-conscious users.

64. etsyweddingteam.com
この記事のおかげで新しい視点を得ることができました。感謝します。

65. bmipas.com
素敵な記事で、読んでいてとても楽しかったです。

66. animehangover.com
Qi Guogong이라는 말을 듣 자마자 Hongzhi 황제는 무의식적으로 Fang Jifan을 바라 보았습니다.

67. bmipas.com
この記事の書き方が大好きです。とてもわかりやすく、インスピレーションを受けました。

68. tvlore.com
주변의 모든 사람들은 의로움을 느꼈습니다.

69. bmipas.com
素晴らしい記事。非常に興味深く、有益でした。

70. game1kb.com
태후는 천천히 젓가락을 들고 죽순을 집어들고 안으로 들어섰다…Taikang 공주는 입술을 오므리며 미소를 지으며 “Xinjian 삼촌, 축하합니다.”라고 말했습니다.

71. ilogidis.com
조상들이 캐릭터를 만들 때 항상 나쁜 취향을 가지고 있었습니다.

72. It’s a pity you don’t have a donate button! I’d without a doubt donate to this excellent blog!
Talk soon!

73. SightCare formula aims to maintain 20/20 vision without the need for any surgical process. This supplement is a perfect solution for people facing issues as they grow older. https://sightcare-web.com/

74. tvlore.com
Hongzhi 황제는 “이제 질문을 할 때입니다 …”라고 진정했습니다.

75. Cacao Bliss is a powder form of unique raw cacao that can be used similarly to chocolate in powder form but comes with added benefits. It is designed to provide a rich and satisfying experience while delivering numerous health benefits. https://cacaobliss-web.com/

76. Utilitylatest provides news and analysis for energy and utility executives. We cover topics like smart grid tech, clean energy, regulation, generation, demand response, solar, storage, transmission distribution, and more. https://utilitylatest.com

77. Lasixiv provides news and analysis for IT executives. We cover big data, IT strategy, cloud computing, security, mobile technology, infrastructure, software and more. https://lasixiv.com

78. Wedstraunt has the latest news in the restaurant industry, covering topics like consumer trends, technology, marketing and branding, operations, mergers https://wedstraunt.com

79. Ellajon provides news and analysis for construction industry executives. We cover commercial and residential construction, focusing on topics like technology, design, regulation, legal issues and more. https://ellajon.com

80. Serdar Akar provides in-depth journalism and insight into the news and trends impacting the packaging manufacturing space https://serdarakar.com/

81. Ladarnas provides in-depth journalism and insight into the news and trends impacting the convenience store space. https://ladarnas.com

82. Sugar Defender is the rated blood sugar formula with an advanced blend of 24 proven ingredients that support healthy glucose levels and natural weight loss. https://omiyabigan.com/

83. Sugar Defender is a revolutionary blood sugar support formula designed to support healthy glucose levels and promote natural weight loss. https://blackboxvending.com/

84. Brilliant writing! You’ve perfectly captured the essence of the topic.

85. The analysis is like a well-crafted movie—engaging, enlightening, and leaving me thinking long after it’s over.

86. zanetvize.com
왕자는 오늘을 가질 수 있고 Fang Jifan은 뗄래야 뗄 수 없습니다.

87. AGENCANTIK
AGENCANTIK says Thank you very much, all the information above is very good and interesting

88. 에그벳
Weizhou Wei는 즉시 격려를 받았으며 그의 용기는 잠시 동안 두 배가되었습니다.

89. 블랙 맘바
그들은 겁에 질려 한 사람 한 사람 주위를 둘러보았지만 감히 작은 소리도 내지 못했습니다.

90. 블랙 맘바
Wang Jinyuan은 메모를했고 젊은 스승이 말한 것만 기억하고 감히 더 이상 말하지 않고 즉시 빠져 나갔습니다.

91. 에그 카지노
4명의 캐릭터 ‘지식과 행동의 통합’이 나오자 누안정의 현장은 갑자기 냉랭해졌다.

93. Get more coins when you purchase from the Zynga Store. The pulsing energy and excitement are felt as soon as you step on the floor! Niagara Fallsview Casino Resort boasts an impressive 200,000 square feet of gaming action – That’s the size of three football fields! Slots Table Games Some of the best online casino websites reward players for placing particularly high bets, often in excess of \$100 per hand. These players are high rollers and enrolled in the casino’s VIP program. High roller bonuses are usually attached to a person’s initial deposit into their account, but this varies from casino to casino. As part of the VIP club, online casinos provide high rollers with lots of free bets, spins, and a range of other exclusive promotions.
https://gardengateslandscaping.com/page/13/
All about action, our High-Limit Slots let you play the widest variety of new and classic high-limit machines. The Invaders from the Planet Moolah® are back and creating pandemoooonium on the reels! The special cow symbols are also back awarding thrilling features and bonuses, including the Unicow! gamespotgiantbombmetacriticfandomfanatical Offering an ever-expanding lineup of new slots! Treasures await at every spin with these new games, Emperor Mystery and Frogged Up. Empire.io can give you big prizes if you enter the tournaments! For instance, the upcoming Grand Multiplier Tournament has a 2K USDT prize pool, where the ultimate winner gets 500 USDT. Moreover, you have a high chance of winning since the tournament will be “held” in the best slot machines to play, like RIP City and Hand of Anubis.

94. 오공 슬롯
하지만… 이 마지막 순간에 그는 자신을 통제할 수 없었다.

95. нейтралитет 15 букв, изнуренков 9 букв день рождения близнецов, что любят близнецы женщины снится творог много,
видеть во сне творог исламский
сонник приметы бабы нины
про беременность, приметы от бабы нины на замужество
сонник малиновое варенье, покупать во сне варенье