-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrays.cpp
More file actions
2236 lines (1983 loc) · 57.5 KB
/
Arrays.cpp
File metadata and controls
2236 lines (1983 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <stack>
using namespace std;
// 287. Find the Duplicate Number
int findDuplicate(vector<int> &nums)
{
int slow = nums[0];
int fast = nums[0];
do
{
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while (slow != fast)
{
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
//KCON (Codechef)
long long maxSubarraySum(int arr[], int n)
{
long long maxSoFar = arr[0];
long long currMax = 0;
for (int i = 0; i < n; i++)
{
currMax += arr[i];
maxSoFar = max(maxSoFar, currMax);
if (currMax < 0)
currMax = 0;
}
return maxSoFar;
}
void KCON()
{
int t;
cin >> t;
while (t-- > 0)
{
int n, k;
cin >> n >> k;
int a[n], b[n * 2];
for (long long i = 0; i < n; i++)
{
cin >> a[i];
b[i] = b[i + n] = a[i];
}
//if k is 1 then simply print max subarray sum
if (k == 1)
{
cout << maxSubarraySum(a, n) << endl;
continue;
}
//calculate maxSubarray sum for A*2 i.e A put 2 times
long long maxSum = maxSubarraySum(b, n * 2);
long long maxPref = -1e9, maxSuff = -1e9, currPref = 0, currSuff = 0, totalSum = 0;
//calculate prefix, suffix, total sum
for (int i = 0; i < n; i++)
{
currPref += a[i];
currSuff += a[n - i - 1];
totalSum += a[i];
maxPref = max(maxPref, currPref);
maxSuff = max(maxSuff, currSuff);
}
//if totaSum>0, then only we should add all repetitions of A, otherwise it will just get smaller with every repetition
if (totalSum > 0)
maxSum = maxPref + totalSum * (k - 2) + maxSuff;
cout << maxSum << endl;
}
}
// Max Circular Subarray Sum
long long maxCircularSum(vector<int> &arr)
{
long long minSum = arr[0], maxSum = arr[0], minSoFar = 0, maxSoFar = 0, totalSum = 0;
//Kadannes algo to calculate minSubarray sum and maxSubarray sum
for (int i = 0; i < arr.size(); i++)
{
totalSum += arr[i];
minSoFar += arr[i];
maxSoFar += arr[i];
minSum = min(minSoFar, minSum);
maxSum = max(maxSoFar, maxSum);
if (minSoFar > 0)
minSoFar = 0;
if (maxSoFar < 0)
maxSoFar = 0;
}
//if all -ve , then return the maxSubarray sum
if (totalSum == minSum)
return maxSum;
//else return the max of maxSubarray or the circular array
return max(maxSum, totalSum - minSum);
}
// Subarray with given sum
/*
Use 2 pointer approach
i=0,j=0
if currSum<tar -> j++
if currSum>tar -> i++
*/
vector<int> findSubarray(vector<int> &arr, int tar)
{
//use two pointer approach
int i = 0, j = 0, currSum = 0;
while (j < arr.size())
{
currSum += arr[j];
if (currSum > tar)
{
while (i <= j && currSum > tar)
currSum -= arr[i++];
}
if (currSum == tar)
break;
j++;
}
//1 based indexing, so i+1,j+1
return {i + 1, j + 1};
}
void findSubarray()
{
int t;
cin >> t;
while (t-- > 0)
{
int n, tar;
cin >> n >> tar;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
vector<int> ans = findSubarray(a, tar);
if (ans[1] > n)
{
cout << -1 << endl;
continue;
}
cout << ans[0] << " " << ans[1] << endl;
}
}
// 724. Find Pivot Index (Equilibrium Point)
/*
Note- The Eq point itself is not part of the left or right Sum
use leftSum, rightSum
find total Sum of array=rsum
start iterating from begin,
lsum=sum+a[i-1]
rsum=rsum-a[i]
*/
int pivotIndex(vector<int> &a)
{
int n = a.size();
if (n == 0)
return -1;
int lsum = 0, rsum = 0; //left = 0 , right = total
for (int i = 0; i < n; i++)
rsum += a[i];
if (rsum - a[0] == 0)
return 0;
rsum -= a[0];
for (int i = 1; i < n; i++)
{
rsum -= a[i];
lsum += a[i - 1];
if (lsum == rsum)
{
return i;
}
}
return -1;
}
// Convert array into Zig-Zag fashion
/*
keep a flag to check required condition nextEle > currEle or nextEle < currEle
if condition is false then swap the two elements
*/
void zigzag(vector<int> &a)
{
int n = a.size();
int flag = 0; //next element should be 0->inc , 1->dec
for (int i = 0; i < n - 1; i++)
{
if (flag == 0 && a[i + 1] < a[i])
{
swap(a[i + 1], a[i]);
}
else if (flag == 1 && a[i + 1] > a[i])
{
swap(a[i + 1], a[i]);
}
flag ^= 1;
}
}
// Find Pair Given Difference
/*
Sort the array
Use 2 Pointer Approach, i=0,j=1
currDiff=arr[j]-arr[i]
while(cond..){
if(currDiff>tar) i++
if(currDiff<tar) j++
}
*/
int diffPair(vector<int> &a, int d)
{
int n = a.size();
sort(a.begin(), a.end());
int diff, i = 0, j = 1;
while (j < n && i < n)
{
diff = a[j] - a[i];
//diff will always be positive, so i<=j is true always
if (diff > d)
{
i++;
}
else if (diff < d)
{
j++;
}
else if (i != j && diff == d)
{
return 1;
}
}
return -1;
}
// Chocolate Distribution Problem (no submission option available on G4G)
int minDiff(vector<int> &packets, int children)
{
sort(packets.begin(), packets.end());
int minDiff = 1e8;
// Find the subarray of size m such that
// difference between last (maximum in case
// of sorted) and first (minimum in case of
// sorted) elements of subarray is minimum.
for (int i = 0; i + children - 1 < packets.size(); i++)
{
minDiff = min(minDiff, packets[i + children - 1] - packets[i]);
}
return minDiff;
}
// Minimum Number of Platforms Required for a Railway/Bus Station
/*
sort both arrival and departure times
then do it like merging two sorted arrays
*/
int getStations(vector<int> &arrival, vector<int> &departure)
{
int n = arrival.size();
int currStations = 0, minStations = 0;
sort(arrival.begin(), arrival.end());
sort(departure.begin(), departure.end());
int i = 0, j = 0;
//we only need to check for arrival array for size check as all trains will arrive first,
//so arrival array will finish first always
while (i < n && j < n)
{
//check for <= as arrival and departure times can be same as well and we need a seperate stations in this case
//train arrives -> currStations++
if (arrival[i] <= departure[j])
{
i++;
currStations++;
}
//train departs -> currStations--
else
{
j++;
currStations--;
}
//update the max stations at a time
minStations = max(currStations, minStations);
}
return minStations;
}
void getStations()
{
int t;
cin >> t;
while (t-- > 0)
{
int n;
cin >> n;
vector<int> arrival(n), departure(n);
for (int i = 0; i < n; i++)
cin >> arrival[i];
for (int i = 0; i < n; i++)
cin >> departure[i];
cout << getStations(arrival, departure) << endl;
}
}
// 373. Find K Pairs with Smallest Sums
/*
using min heap
the approach is similar to merging K sorted Lists using Priority Queue
*/
struct compareSum
{
bool operator()(const vector<int> &v1, const vector<int> &v2)
{
return v1[0] + v1[1] > v2[0] + v2[1];
}
};
vector<vector<int>> kSmallestPairs(vector<int> &nums1, vector<int> &nums2, int k)
{
if (nums1.size() == 0 || nums2.size() == 0 || k == 0)
return {};
vector<vector<int>> ans;
priority_queue<vector<int>, vector<vector<int>>, compareSum> pq; // {nums1[i], nums2[j], j}
//form pairs with the first element of num2 with all elements in num1
//so we add all (0,0), (1,0), (2,0)........(n-1,0) into PQ
for (int i = 0; i < nums1.size() && i < k; i++)
{
pq.push({nums1[i], nums2[0], 0});
}
//for each pair removed from PQ push the pair with next largest sum into it
//we have a choice to add either (i,j+1) or (i+1,j), but we only add (i,j+1)
//as the (i+1,j) we already be in the PQ or not qualified.
//PQ is of size K
while (k-- > 0 && pq.size() != 0)
{
vector<int> pr = pq.top();
pq.pop();
//add the top of PQ into the answer
ans.push_back({pr[0], pr[1]});
if (pr[2] == nums2.size() - 1)
continue;
//next largest sum will be given by the next element of nums2 from the element removed from PQ
pq.push({pr[0], nums2[pr[2] + 1], pr[2] + 1});
}
return ans;
}
// 26. Remove Duplicates from Sorted Array
/*
Use two pointer approach O(n)
if(a[i]==a[j]) then only j++
if(!=) a[i+1]=a[j];
i++;
j++;
*/
int removeDuplicates(vector<int> &nums)
{
if (nums.size() == 0)
return 0;
int i = 0, j = 1;
while (j < nums.size())
{
if (nums[i] != nums[j])
{
nums[i + 1] = nums[j];
i++;
}
j++;
}
return i + 1;
}
// 153. Find Minimum in Rotated Sorted Array
/*
use binary search
if arr[mid]<arr[hi], then smallest element i.e. pivot lies in left region i.e. region<=mid
else it lies in right region i.e. in region>mid
*/
int findMin(vector<int> &nums)
{
int lo = 0, hi = nums.size() - 1;
long mid;
while (lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] < nums[hi])
hi = mid;
else
lo = mid + 1;
}
return nums[lo];
}
// 154. Find Minimum in Rotated Sorted Array II (Duplicates allowed)
/*
if arr[mid]==arr[hi], then we have no choice but to do a linear search in whole array,
as we cannot decide which part pivot lies in.
So in that case we just reduce the hi by 1
*/
int findMin(vector<int> &nums)
{
//Worst case: not rotated array, O(n)
int lo = 0, hi = nums.size() - 1;
long mid;
while (lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] < nums[hi])
hi = mid;
else if (nums[mid] > nums[hi])
lo = mid + 1;
else
{
/*if (i-1)th is greater that means (i)th will be the pivot
eg- 1 1 1 1 2 1 1
here at i=5 , a[i-1]>a[i] and i is the pivot index
*/
if (nums[hi - 1] > nums[hi])
return nums[hi];
hi--;
}
}
return nums[lo];
}
// 33. Search in Rotated Sorted Array
int search_01(vector<int> &nums, int target)
{
int lo = 0, hi = nums.size() - 1;
long mid;
//find smallest element(pivot)
while (lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] < nums[hi])
hi = mid;
else
lo = mid + 1;
}
//find which region target lies in
int pivot = lo;
lo = 0, hi = nums.size() - 1;
if (target <= nums[hi])
{ //right half of pivot
lo = pivot;
}
else
{ //left half of pivot
hi = pivot - 1;
}
//normal binary search in that region
while (lo <= hi)
{
mid = (lo + hi) / 2;
if (target < nums[mid])
hi = mid - 1;
else if (target > nums[mid])
lo = mid + 1;
else
return mid;
}
return -1;
}
int search_02(vector<int> &nums, int target)
{
int lo = 0, hi = nums.size() - 1;
long mid;
//find smallest element(pivot)
while (lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] < nums[hi])
hi = mid;
else
lo = mid + 1;
}
//binary search accounting for rotation
int rot = lo, n = nums.size();
lo = 0;
hi = n - 1;
while (lo <= hi)
{
int mid = (lo + hi) / 2;
int realmid = (mid + rot) % n;
if (nums[realmid] == target)
return realmid;
if (nums[realmid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Given a sorted and rotated array, find if there is a pair with a given sum(Not available for submission)
bool pairSum(vector<int> &nums, int target)
{
//find pivot
int lo = 0, hi = nums.size() - 1;
long mid;
while (lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] < nums[hi])
hi = mid;
else
lo = mid + 1;
}
//use 2 pointer method(meet in the middle) using mod to keep index in range
int pivot = lo, n = nums.size();
int i = lo, j = pivot - 1;
//i goes pivot -> n-1 , j goes pivot-1 -> 0
while (i != j)
{
if (nums[i] + nums[j] < target)
{
//to keep i++ in range
i = (i + 1) % n;
}
else if (nums[i] + nums[j] > target)
{
//to keep j-- in range
j = (n + j - 1) % n;
}
else
return true;
}
return false;
}
// 525. Contiguous Array
/*
we do count-- for 0s, and count++ for 1s
keep a map for count:index values
two index where count is equal, will have equal number of 0s and 1s, so at each index we just check
if this count value is present in map and update the max subarray length
*/
int findMaxLength(vector<int> &nums)
{
int count = 0, maxlen = 0;
unordered_map<int, int> mp; //{count:index}
mp[0] = -1;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 0)
count--;
else
count++;
if (mp.find(count) != mp.end())
maxlen = max(maxlen, i - mp[count]);
else
mp[count] = i;
}
return maxlen;
}
// 121. Best Time to Buy and Sell Stock
/*
Just find the max diff in array
Keep a min so far for each element, and update the maxProfit with the max diff i.e arr[i]-minSoFar
*/
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int maxp = 0, minSoFar = prices[0];
for (int i = 0; i < prices.size(); i++)
{
minSoFar = min(minSoFar, prices[i]);
maxp = max(maxp, prices[i] - minSoFar);
}
return maxp;
}
// 122. Best Time to Buy and Sell Stock II
/*
Approach 1-
while the price keeps increasing keep adding it to profit,
when it decreases, dont include it
*/
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int totalProfit = 0;
for (int i = 0; i < prices.size() - 1; i++)
{
if (prices[i + 1] > prices[i])
totalProfit += (prices[i + 1] - prices[i]);
}
return totalProfit;
}
/*
Approach 2-
keep a currMin (for the current rise in price),
the moment the price drops, you sell the stock and add arr[i]-currMin into the total profit
*/
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int currMin = prices[0], totalProfit = 0;
for (int i = 0; i < prices.size() - 1; i++)
{
if (prices[i] > prices[i + 1])
{
totalProfit += prices[i] - currMin;
currMin = prices[i + 1];
}
}
totalProfit += prices[prices.size() - 1] - currMin;
return totalProfit;
}
// 123. Best Time to Buy and Sell Stock III
/*Approach 1-
Make a prefix and suffix array
Prefix- Stock is sold on this day
Suffix- Stock is bought on this day
Then the max profit the max sum of prefix and suffix arrays
*/
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int n = prices.size();
vector<int> prefix(n), suffix(n);
//we can maintain the max Profit so far seperatly,
/*
int minBuying = prices[0], maxProfitSoFar = 0;
for (int i = 0; i < n; i++)
{
minBuying = min(prices[i], minBuying);
maxProfitSoFar = max(maxProfitSoFar, prices[i] - minBuying);
prefix[i] = maxProfitSoFar;
}
int maxSelling = prices[n - 1];
maxProfitSoFar = 0;
for (int i = n - 1; i >= 0; i--)
{
maxSelling = max(maxSelling, prices[i]);
maxProfitSoFar = max(maxProfitSoFar, maxSelling - prices[i]);
suffix[i] = maxProfitSoFar;
}
*/
//or we can just use the value in i-1 index, as it already has the max value upto that point
int minBuying = prices[0];
prefix[0] = 0;
for (int i = 1; i < n; i++)
{
minBuying = min(prices[i], minBuying);
prefix[i] = max(prefix[i - 1], prices[i] - minBuying);
}
int maxSelling = prices[n - 1];
suffix[n - 1] = 0;
for (int i = n - 2; i >= 0; i--)
{
maxSelling = max(maxSelling, prices[i]);
suffix[i] = max(suffix[i + 1], maxSelling - prices[i]);
}
int maxp = 0;
for (int i = 0; i < n; i++)
{
maxp = max(maxp, prefix[i] + suffix[i]);
}
return maxp;
}
//Approach 2 (faster)-
int maxProfit(vector<int> &prices)
{
int sell1 = 0, sell2 = 0, buy1 = 1e8, buy2 = 1e8;
for (int i = 0; i < prices.size(); i++)
{
buy1 = min(buy1, prices[i]);
sell1 = max(sell1, prices[i] - buy1);
buy2 = min(buy2, prices[i] - sell1);
sell2 = max(sell2, prices[i] - buy2);
}
return sell2;
}
// 188. Best Time to Buy and Sell Stock IV (Not Complete)
int maxp; //max profit
//shares==1 -> have an extra share, so can only sell
//shares==0 -> dont have a share so can ony buy
//Recursion
//void type
void maxProfit_rec1(int shares, int profit, int K, int idx, vector<int> &prices)
{
maxp = max(maxp, profit);
if (K == 0 || idx == prices.size())
{
return;
}
//buy
if (shares == 0)
{
maxProfit_rec1(1, profit - prices[idx], K, idx + 1, prices);
}
//sell
else
{
maxProfit_rec1(0, profit + prices[idx], K - 1, idx + 1, prices);
}
//do nothing
maxProfit_rec1(shares, profit, K, idx + 1, prices);
}
//return type
int maxProfit_rec2(int shares, int profit, int K, int idx, vector<int> &prices)
{
if (K == 0 || idx == prices.size())
{
return profit;
}
int maxp = 0;
//buy
if (shares == 0)
{
maxp = max(maxp, maxProfit_rec2(1, profit - prices[idx], K, idx + 1, prices));
}
//sell
else
{
maxp = max(maxp, maxProfit_rec2(0, profit + prices[idx], K - 1, idx + 1, prices));
}
//do nothing
maxp = max(maxp, maxProfit_rec2(shares, profit, K, idx + 1, prices));
return maxp;
}
int maxProfit(int k, vector<int> &prices)
{
return maxProfit_rec2(0, 0, k, 0, prices);
}
// 714. Best Time to Buy and Sell Stock with Transaction Fee
int maxProfit(vector<int> &prices, int fee)
{
if (prices.size() == 0)
return 0;
int maxAfterBuy = -prices[0]; //current cash in hand after buying
int maxAfterSell = 0; //current cash in hand after selling
for (int i = 1; i < prices.size(); i++)
{
maxAfterBuy = max(maxAfterBuy, maxAfterSell - prices[i]);
maxAfterSell = max(maxAfterSell, maxAfterBuy + prices[i] - fee);
}
return maxAfterSell;
}
// 309. Best Time to Buy and Sell Stock with Cooldown
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int maxAfterBuy = -prices[0]; //current cash in hand after buying
int maxAfterSell = 0; //current cash in hand after selling
int prevMaxSell = 0; //max cash after cooldown(stores the max sell just before cooldown)
for (int i = 1; i < prices.size(); i++)
{
int prevMaxBuy = maxAfterBuy;
maxAfterBuy = max(maxAfterBuy, prevMaxSell - prices[i]);
prevMaxSell = maxAfterSell;
maxAfterSell = max(maxAfterSell, prevMaxBuy + prices[i]);
}
return maxAfterSell;
}
// Maximum Difference (given that second element is greater than first element)
int maxDiff(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int maxp = 0, minSoFar = prices[0];
for (int i = 0; i < prices.size(); i++)
{
minSoFar = min(minSoFar, prices[i]);
maxp = max(maxp, prices[i] - minSoFar);
}
//if no secondEle > firstEle then return -1
return maxp == 0 ? -1 : maxp;
}
int maxDiff()
{
int t;
cin >> t;
while (t-- > 0)
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << maxDiff(arr) << endl;
}
}
// 56. Merge Intervals
vector<vector<int>> merge(vector<vector<int>> &intervals)
{
if (intervals.size() == 0)
return {};
vector<vector<int>> res;
//sort the array
sort(intervals.begin(), intervals.end());
res.push_back(intervals[0]);
int j = 0;
//for each interval check if it overlaps with last one, and add it accordingly
for (int i = 1; i < intervals.size(); i++)
{
//if it overlaps, merge the two intervals
if (intervals[i][0] <= res[j][1])
{
res[j][0] = min(res[j][0], intervals[i][0]); //start will min of both starts
res[j][1] = max(res[j][1], intervals[i][1]); //end will be max of both ends
}
//if it does not overlap, just add it
else
{
res.push_back(intervals[i]);
j++;
}
}
return res;
}
// 57. Insert Interval
vector<vector<int>> insert(vector<vector<int>> &intervals, vector<int> &newInterval)
{
if (intervals.size() == 0)
return {newInterval};
vector<vector<int>> res;
int idx = 0;
//push all intervals less than newInterval into res
while (idx < intervals.size() && intervals[idx][1] < newInterval[0])
res.push_back(intervals[idx++]);
//find and push the merged Interval into res
int mergedStart = newInterval[0], mergedEnd = newInterval[1];
while (idx < intervals.size() && newInterval[1] >= intervals[idx][0])
{
mergedStart = min(mergedStart, intervals[idx][0]);
mergedEnd = max(mergedEnd, intervals[idx][1]);
idx++;
}
res.push_back({mergedStart, mergedEnd});
//push the remaining intervals into res
while (idx < intervals.size())
res.push_back(intervals[idx++]);
return res;
}
// 75. Sort Colors (3 Way Partition)
void sortColors(vector<int> &nums)
{
int lt = 0, gt = nums.size() - 1, i = 0;
while (i <= gt)
{
//left region: i++, lt++ (after swapping element will definitely belong to left region)
if (nums[i] < 1)
{
swap(nums[lt++], nums[i++]);
}
//right region: only gt-- (because after swapping we could get an element that may belong to left or middle region)
else if (nums[i] > 1)
{
swap(nums[gt--], nums[i]);
}
//middle region: i++
else
i++;
}
}
// Three way partitioning
vector<int> threeWayPartition(vector<int> nums, int a, int b)
{
int lt = 0, gt = nums.size() - 1, i = 0;
while (i <= gt)
{
if (nums[i] < a)
{
swap(nums[lt++], nums[i++]);
}
else if (nums[i] > b)
{
swap(nums[gt--], nums[i]);
}
else
i++;
}
return nums;
}
// 912. Sort an Array
void mergeSort(vector<int> &arr, int si, int ei)
{
if (si == ei)
return;
long mid = (si + ei) / 2;
mergeSort(arr, si, mid);
mergeSort(arr, mid + 1, ei);
merge(arr, si, mid, ei);
}
void merge(vector<int> &arr, int si, int mid, int ei)
{
//make a temp res array, to store sorted list, then copy it into original array
//size of res= ei-si+1, but it will be initialized by zero if you provide size,
// so will have to use an index instead of push_back
vector<int> res;
int i = si, j = mid + 1; //start index of both halfs
int n = mid + 1, m = ei + 1; //end index of both halfs
while (i < n && j < m)
{
if (arr[i] < arr[j])
res.push_back(arr[i++]);
else
res.push_back(arr[j++]);