Arrays
Arrays
2L0003I1)S
2. intC] arr =
3. int arrC ] 2, 5, 4,5,64
Dishdvantaqeir
Advantaqe 'itubo fiked Site
¿lemens Con be Accened directly'
USing aeir index.
it Con shore only Single dataype.
2. it Allocate Conliquus nerorg, Making
memory - eficenf"
taem mengrq
3- inserling And deleling eleed may
3. 8irgle and Skoightfotoand to dedlave Tequire shifing other elemenk, :
and Use.
ari] St-nex\intt),
it (ai]--key)
SopC'no tound')
2. Lagest Nober:- find the largest number in a giren Anay
else
3 Binay Search;
vsed for findng te element's Posiliorn in a Borted Array-
ilis
Nauer
2l0003|S
midd (short +end)fa ende-l
starlo
id-Ky
Mindekay
teadable.
Psevdo Code'- Simplified And humon
SBart o ,end =n-l
uhile (Stat &end)
Find id
’ Conpane mid &
eKoay
Code': Tine Complenl:
int storl =0 ,end enlengta-;
iteraion h
uhile ( Starte end)
.itevation h . !
mid (Start t end)/2:
ikeraton
if (hemid -- key) 4.iteraliornl8 -
retorn mid;
last
’ for
prining the otput
Yeverse c) in Main fonclion
for Cint i-o; iLn-lengt; iH)
Syatem oot"pint (ni4 ");
S- Poirs in an 246|8 10
2’ (4) (2:6) (,8) (10) 4 Total pairs
4 (4,6) (4,8) (410)3
6 (68) (G0)
Nayeem
2,4,6 2,4,6, 8 2,4, 6, &,10 >s 21000 %11S
2,4
logic:
- Findue start for (int ieo lon)
end for ( int j-it 4on)
, Find tue
Find Stort and end For (sfart to end)
3-
Code' in Total subarrayse 0)start 2
æjend 46,8,10
For Cint i-0; izn-lengty i44)
int starti;
for (int j*i: jenlengte it)
int end =j;
kzend k)
for ( int k- Stort,
Siop (on()
Sopht;
sop (4Total Sub anvay);
Add Sorge Conditions:
Riot Surm of the Cunrent subanoy.
2. Update minsum and maxSum.
Sum: 20 Sum:28
Max Subarray Sum (BRUTE foRc)
21000 b1|15
()1 Apptoseli'r
Mox 3ubaras'
(\2) ’ We oant To Take Vaniable
Value and "Corent Sum
(0-2,6) >s qve, tue Maximurn
uhich
of subarYay
(,-2,6,-)4 qive, te (orrent Sum wita Coireat
Marsobavray
’ taen we vpdak tue
Surm
Code:
int Current Sum O,
oukput
Inteqev.-MIN-VALlwE,
int max Sum: (-2) -
for (int i o, iLan:lengt i+) (,-26)> s
For (intji; jLr-leg;jt)
Cuventsom =0; (,-,6,-,)’7
for (int kei; Kuj; k4)
S"opln (Maxsum)
(6,3)>8
G,s) 2
Tine Compleriy
3bop: go
lon-Oo) Mox Sum ’8
uy Refir Anay Tme Conpliy On) Naeery
3
{or (stal ke end)
de
in he place of loo Add the Preßik formula To
-2+6161)
Sopn('ira
max Sum+ maxSum);
) kADANC's
+Ve
+Ve
4Veceig) t -Ve(tran)’
(Bg)Ye
4VeCorau)4 -Ve
4-1
(ode
7-21474a14 7
-21414794:0
in Polk ntij- byuphce;
buyie ni,
lrln mopoi
(44614 ) M (o,-);
e)
5-7
M(o4)
() (1e6)
N(O1)
q Taging Roinwatev 1aueen
210003H1
Given n on. negdive inkeqprs tepveenling an erlevion Map there the cid te
of eah bar is 1, Conpute houw fmuth water it con trap after vain1g
oe want b know tae H much wdker is slored in blw tue kars
i
we have a Sinple fermch
logic
r waterlevel -’ (Maxlet Moxkgh)
Tapped water ’ (onkertevel - hight)
To Find Molaiglt
’Use Aray
Left max boundary :- M4L]
max
Nlaueen
Code' 2\00031|1S
Roblic salie inint apedBinaler (w bighit) Tine Compleal Oun
inl n heigh length
lCaleulale legl may bouhdary voy
fi-1)y
let mar fid . Matl max ((heghtfi1, etmag
Il Caleulale Righl max boUndany -Aay
inl Right max(3: nw int (eighntongil
Rig max(h--height fn-1
for( int ixh-2; i>0; i--)
ra,(i41)2
RighB mox ti - Matlmax (heighicii, Right
l loop int Trapedwater -0;
for (int i=o, ien;i4)
int waterlevel Matlmin (legtmaxti , Righimar ti)
ragpedaler t= uatolevel -heightrid,
, Tekn Tappedualev;
Paclical 6Queslions
Nauee
find Hue duplicae values. if ere pint "roe 2\000311S
Seladd (nc
So pln ('False ); ,relorn fale,
2 Count No ot 2evos
Code'
Poblie Stakie void Count (ink nc)
int (oont0)
i)
for Cinl I-o; ie nlengtay
(ount 44}
Sop ("oun!")
eteq
Sop)
8 Right Rotate:
Nayeem
21000311IS
42 Tiapping Roin waler:-(hard)
height (o,,0,2,!,0,,3,2,,2,1)
Joguti-
vepeenled
Explaraion- The above elevakon mop is 2,].
2,,
by Aray (o,, 9,1) ,0,,3,vain water
unib of
in tis Cac, 6
are being trapped
Algo: eqval to 2, Yekoning9 0if rue a
lengt is len than or
PHChecka ithe inpot Aray
Nopping water Yecuives at leot s bars and vight maximom
and'righkMax', are Cveated to sfore the left
oo Aray, leftmax
for each
heighl bor index
tae keft marimum heighks by {raversing tue'height Avay From left
3 The Ago Calcolates
to righl
4 ximum heighh by kroversig tue 'heighl' Array
it Calcolates the ight maximum from
Simlay
SA variable 'rappedwokev is iniiali2ed ko 0 stove the kotal trapped waker
( The Algokerates trough tue 'heighf Aray Calalaing -te Traped water at each index
baed on te Mirieu of legt and vight maximun heights minus tue orent high
7. The Rewlt is skored in the 'Eroapped waler variable
Time Congieay
Spote Corgleiy: Oln
Code 2
int ( le{max
int Jrighmor
I| Calculale legt moxinm heights for each index
leftror (o] height(o3;
letmox (i1 Matt-max (legtmax ti-), height Ci1);
vight maximum
Yighlmax n-4-height (n-:
for( int in-2; i20, i-
ightmax i3 -Malumax (rightMax ti+1, height ti);
I Cglculat lrapped water at each index.
ink ragpedwater eo,
for int ie o i4n, it+t)L Mar
Rght Mor
Min -o):
I2, Best Time to Buy and sell stock (tany)
Noyen
LI00031I
inie goor hoft by choing a Sogle day bo bay One stock and
Chocing a djerent day hthe fohoe to sel that skock
Telorn the moximom profi gou can Achieve from his fon saclion it you (annot
Achieve Ary Profit, tekon
Yelovn o''o!.
Inpt- Picos (3
oulpul s
Eplanaken: Buy on daye (ite ) and sellon day s(Pie:4) . Proit:1:5
Code- 06)
int buy - Pritesbk,
int moxprofit -c)
for (int i-o;
izpices.lergtii)
tCbye pite,tu)
in profi Pieoig -boy buj
max pirofi Metumax (ena pofihr profi);
else
elon moxprefib
{5
Prfi|-4
12 Best Time to Buy and sell skock i Noaueen
210003111S
day you may decide ko by andlor sell the stock. You Can onky hold at
Un each
at any Time. Hootver, you ton boy ten imm dhatey
nost one Shore of tue stock
Sell on the Same doy
Find and relrn tue maximym profit yov Con Achieve.
Jnpul- Ric - (3,5, 3,6)
and sell on days (Pice-s),Profit s:4
xplanalion :- Bug on day2 (Pice-i)
-6), Profite 633
on day s (Price
Ihen buy on day 4 (Price=3) and Sell
Total Profit is 443-t
L4,,5, S,{, 4]
Code:-0(6)
I>X
int maxproftit =0,
S ) s-94
for (int i- , iz prieslengtu i4) 1 375
6>3 6-3 ’3
t(Price, cij- Price,ti-)
4+397
rekurn moxProiti
S3 Maximum Subaray (Medium) Nayoem
21000311IS
Given an ineqer Avay (mun), jind tue Sobaroy wit te larqut Som, and Te
ter4-) (2, )
’ (1) (2,1) (2, ,-3) (2,,-s,4) (-2,l, -3,4,-)
C2;\,-3,9,-, ,,5) (2,,-3,4-\,44')
-2
-4
’ ,1,-3,)=42-444-0
’ (2,4,-3, 4,-1,) =l
’ ¢2,|, -3,4,-1, 2,) e4
|2, 1, 3, 4, ,9, )
(owent sum
(uwentsum - t
-24 -Se-3
344|
{(Corentsom >moraum)
naxsum e (orrenbum;
4Ve 4 +Ve
maxu L
Manhm-l
-320
’44
Maxlayr Marway
’3+2
4+!
maxwI Moxlaye -5 maxsumy
MaKo
maxa4
-SI6
Optimi2ed:-g
int Cwwent Sum- 0,
it (rentsaum co)
lelalle
higt-5
Code- O)
n ans -0 Noyeern
210003|||S
int let 0)
int tighnt heighk. lengta-t
while (legye igh)
int lengti Matt min (heighlt UeJ, higs GighN))
ins breath vighk -legt
int Areac: lengta * bueayy
ns Ma max,(ons, Area))
legtty.
else
Yight -
Yeluro ans;
(84 Rotate Aay (Medum) Nayee
21000 3I|15
Given an integer Amay (rom), otate the Aroy lo tae tight by 'k', skeps, here
'knon- negaive
k
Inpti- nums C4,2,s4s6,1),
Oulput- [s.4,1,,1,54]
Explonal'on:
totake steps to he light [4,2, s4, 5,6]
(13,9,s,43]
totale 2seps ko the Hight Is,6,4,,34)
totake seps o the vighl-
3
3 4
S 6 Rotate Rigtt by kshep
+ Revevse Aray
6 Spae Comçleiy Co)x0)
I-Reverse whale Aray
ke31.6=2
1 Reverne k elemert
element
2 1 3' Reverse n-
k- ky. site
chohan approath!
TC! 0cny n -k K
Tenp aray L SC. 0cn
for( int in-k ien,)t+)
Tenpcinda4]: original avvaci)
original avy
lor cint izo, icn-kyitt)
Temp Cindex *+J= originaavrayci
Code 12
K - K7.num lengta,
Yoblic stakc void tevevte ( int (3 hums, int stort, int end)
Code'
Poblie int remove Dopli cales (int C]ouns)
i{C noms-lengt =-o)!
rekovn 0
int i-o;
for (intj- (y jenomsleng;jH)
teturn i+
13 3Sumn (Medium)
(numso,fens(, nuns(«)
Given an eger Avay nynt, reon all the higlets (hum 6o,
and j!k, and noms(0+ noms(jJ+ numsJ0
The distint Triplels are (-\,0, ) and -l, -, 2]. Triplek does not matter.
and te order of-the
Nolice that tue Order of the ootput evorsi
Sample Code wit
Agproac: Poblic void -tareeom (int
(Javy, int Targe
t- Sort Aray Avayg-sort(am):
2 Use thue tree pointer jj.k) forCint i-o;&icarenga; itt)
jeu) (oe1) iN jei+
Su itj +h ’ -lto+I
hhile (jek)
L
-l,0,!
it (Sum=a arget)
(1:
Jop(anti)+,"4avt) + "4anl):
etse
K-
Geks tor qeeks Naueern
Choco late Dislibolion Roblem 2\000 3111S
N inheqers where eoch vabe tepresena tt No of chollaey in apackot toth
distribote
Parkel Can have a Vaiable Ao of chotolales Thore are Mshudenb,the task islo
chotelote Packeb such tot
* Each sludent ges One Pockel
chocolae, cnd tae
The ditferene between te No of cheolotes ntse Pachet otth moximun
Pachet wth minimUm chocolgkes aivea o the students is minimum
Example
npot:- an] -{1,3 2,4,4,12, 56y,m3
Outpol:- Miniom difevence is 2
Cxplanation:- we have Seea Seren Rackek of chocolaBes and we need to pick -taree Paches for s
Sudenk
and minimu acker
TOC pick 2 3 and 4, we aet he Minimom difference bekoeen Maximum
nin.diff - NL MAX
Soied Anay'
6 Alayeer
2\0008111S
g'’ 4
Step- I:
itn-!
4
sBep-:
I+3-!
’3
norting
4-2> min - diff (2) ·Do
S6
Step-q 343-1
int n: o leng
int Ans J teger. MAX.VALUE,
vay. Sorl (on);
for( inl iro; 14 n-; i4)
int min afi3;
inl mox a[itm-];
int gop "max-nin,
it Cgap zans)
ans 9ap)
Youvn ans,
Poblic stalic void main
int(3 arr 13,3, 2, 4,9, 12, 54;
int me 3
Sep(Find (avr, m)
Iner view Bit 2
breck);
Gode' Brue tovce
Int n alengte
21000311s
int tepeating:, Misingb
for (int i- ini4) Aprooch
int Coont -O;
Orrunente in the
».fov eoch inter, , oe willCount is
fer (int jojenj") given Airay vsing (ineor Seoeh.
3 we orll store ose oo
elemenh -hat have tue
{ (acj aio)
Ocowente of ) and 0
Ceuni 44)
iCeort ) lepealing
else if Crunt eo) miting Time Conpleaiy Ocw)
(repeatng ! missing ) Spae Compleaih 00)
break,
Mat'
OSing 4 2+ 3+4.. n. Dx(ot)
Qr: 4 3 6 2I]
*’ Repealing
So
(t-5)
Repee
( t ) -24
[>Bepealing
23
2l000311|5
Hior to be ing pased to your funelion, 'nons' is po sibly Yotated at an unknan pive
Index K(Ie Ks, munglengk Soch tatthe tesuling Aray is rons (u),um:(wil, , (0-1ndexe .
To ¿xnole Lo.,2,4, S, 6, 1] might be tolated af Pivot index 3 and becone [uSi6,4,0,2].
huns agler the posible totalion and on inleqev orget', vekorrn toe inser of
Given the Anay
'nom'.
targel { iFis in nums',oris not in
You most wvite An Algoitiy oit O(rgn) online omplei
Inpoti- UmS - (4,S,6, 7,&,91,!], lavget o
’ l42
’ eliminate Ohe halt
let hond Side
In Cane of the larget 8
842 X y then kis never lie on the let holt
’ for the given Prbl we Cannot eheck the One half beCaute il
is not &ovted.
ke nums (midi)
f (omy(low] k e
Ilelerent exish
high mid-;
else
L lelemeot doe not exist
louy - mid +
high: mid-b
leetcade
Element inan Avray [ Medim] Nayeer
215. Ktu Largest 21000311
klarget
aqet element in
iivn an ntegen Aoyoms ond on integer 'k", rehoro te
the Anay not the 'uk
'k" element in tue Sorted order,
Note that i the is he larqest
distinct element
Can Solve
2 S6
3
3
3 3
Sort 6
Code' Nayer 29
210003115
t noms, int k)
int find KttaLarqest (vector eint Order
end), greater zint7(i); I| de stending
Sot (numsbeginc),nomns
Yeturo Nums [k-j;
And tacre is a Anoter Oplini 2ed Aopvoachi the Top largest elenenhis there)
Heap > Max Heap (at
Min Heap
S
3 2
Max heap
log o
(logr)
’ adding in he morheap
Moz heap TC:- (nbg)
’ insevt all elemenb in
(k-i) ime, fron maxheap
’ we pop element
max heapr
’ The lop of
(spate Conpleciy
The Oplini |ed ieoeSC:-0(K)
Te:- nbgk
Klargo
grealett>Min htap
Max
3 S 6
L K2
fiyst k een 2\00031|)5
’in Minheap elemend
we will have k
Akoay in min heap elem onta
’ Min Heap (onlinules Top K-
Code'
Poblic int findka Larqet (intL J nums, int k)