Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bab7fef

Browse files
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)

AltStyle によって変換されたページ (->オリジナル) /