Skip to content

Commit 86c6445

Browse files
committed
Array techniques
1 parent 80e7c60 commit 86c6445

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

Data Structures/Array/index.js

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,103 @@ function productsFollowingUp(input) {
6464
}
6565

6666
console.log(productsFollowingUp([1, 2, 3, 4, 5]));
67+
68+
/**
69+
* Locate smallest window to be sorted
70+
*
71+
* Given an array of integers, determine the smallest bound of window that must be sorted in order for
72+
* the entire array to be sorted.
73+
*/
74+
75+
function smallestWindow(input) {
76+
if (input.length === 0) return [];
77+
78+
const inputSorted = [...input].sort((a, b) => a - b);
79+
80+
let left = null;
81+
let right = null;
82+
for (let i = 0; i < input.length; i++) {
83+
if (input[i] !== inputSorted[i] && left === null) {
84+
left = i;
85+
} else if (input[i] !== inputSorted[i]) {
86+
right = i;
87+
}
88+
}
89+
90+
return [left, right];
91+
}
92+
93+
console.log("smallest window: ", smallestWindow([3, 7, 5, 6, 9]));
94+
95+
function smallestWindow2(input) {
96+
if (input.length === 0) return [];
97+
98+
// Determine right bound
99+
let currMax = Number.MIN_VALUE;
100+
let right = null;
101+
for (let i = 0; i < input.length; i++) {
102+
if (input[i] < currMax) {
103+
right = i;
104+
} else {
105+
currMax = input[i];
106+
}
107+
}
108+
109+
// Determine left bound
110+
let currMin = Number.MAX_VALUE;
111+
let left = null;
112+
for (let i = input.length - 1; i >= 0; i--) {
113+
if (input[i] > currMin) {
114+
left = i;
115+
} else {
116+
currMin = input[i];
117+
}
118+
}
119+
120+
return [left, right];
121+
}
122+
123+
console.log("smallest window 2: ", smallestWindow2([3, 7, 5, 6, 9]));
124+
125+
/**
126+
* Calculate maximum subarray sum
127+
*
128+
* Given an array of integers, find the maximum of continuous subarray
129+
*/
130+
131+
function maxSum(input) {
132+
if (input.length === 0) return 0;
133+
134+
function sumArr(i, j) {
135+
let sum = 0;
136+
for (let k = i; k <= j; k++) {
137+
sum += input[k];
138+
}
139+
return sum;
140+
}
141+
142+
let currMax = Number.MIN_VALUE;
143+
for (let i = 0; i < input.length - 1; i++) {
144+
for (let j = i + 1; j < input.length; j++) {
145+
currMax = Math.max(currMax, sumArr(i, j));
146+
}
147+
}
148+
149+
return currMax;
150+
}
151+
152+
console.log("max sum: ", maxSum([1, 2, 3, 4, 5]));
153+
154+
function maxSum2(input) {
155+
if (input.length === 0) return 0;
156+
let maxAtIndex = 0;
157+
let maxGlobal = 0;
158+
for (let i = 0; i < input.length; i++) {
159+
maxAtIndex = Math.max(input[i], maxAtIndex + input[i]);
160+
maxGlobal = Math.max(maxGlobal, maxAtIndex);
161+
}
162+
163+
return maxGlobal;
164+
}
165+
166+
console.log("max sum 2: ", maxSum2([34, -50, 42, 14, -5, 86]));

0 commit comments

Comments
 (0)