Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit bab7fef

Browse files
authored
Create 1802. Maximum Value at a Given Index in a Bounded Array
1 parent 1a7763d commit bab7fef

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//Bruteforce - O(Steps OR Result)/ O(1)
2+
class Solution {
3+
public int maxValue(int n, int index, int maxSum) {
4+
int res = 1;
5+
maxSum -= n;
6+
int left = 0, right = 0;
7+
int maxLeft = index, maxRight = n - index - 1;
8+
9+
while(maxSum > 0) {
10+
res++;
11+
int leftVal = Math.min(left++, maxLeft);
12+
int rightVal = Math.min(right++, maxRight);
13+
maxSum -= (1 + leftVal + rightVal);
14+
}
15+
return (maxSum<0) ? res-1 : res;
16+
}
17+
}
18+
19+
20+
//Optimized - O(N)/O(1)
21+
class Solution {
22+
public int maxValue(int n, int index, int maxSum) {
23+
int res = 1;
24+
maxSum -= n;
25+
int left = 0, right = 0;
26+
int maxLeft = index, maxRight = n - index - 1;
27+
28+
while(maxSum > 0) {
29+
res++;
30+
int leftVal = Math.min(left++, maxLeft);
31+
int rightVal = Math.min(right++, maxRight);
32+
maxSum -= (1 + leftVal + rightVal);
33+
34+
if(leftVal == maxLeft && rightVal == maxRight) {
35+
break;
36+
}
37+
}
38+
39+
if(maxSum > 0){
40+
res = res + (maxSum/n);
41+
}
42+
43+
return (maxSum<0) ? res-1 : res;
44+
}
45+
}

0 commit comments

Comments
 (0)