-
Notifications
You must be signed in to change notification settings - Fork 26
/
1802. Maximum Value at a Given Index in a Bounded Array
101 lines (82 loc) · 2.29 KB
/
1802. Maximum Value at a Given Index in a Bounded Array
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
//Bruteforce - O(Steps OR Result)/ O(1)
class Solution {
public int maxValue(int n, int index, int maxSum) {
int res = 1;
maxSum -= n;
int left = 0, right = 0;
int maxLeft = index, maxRight = n - index - 1;
while(maxSum > 0) {
res++;
int leftVal = Math.min(left++, maxLeft);
int rightVal = Math.min(right++, maxRight);
maxSum -= (1 + leftVal + rightVal);
}
return (maxSum<0) ? res-1 : res;
}
}
//Optimized - O(N)/O(1)
class Solution {
public int maxValue(int n, int index, int maxSum) {
int res = 1;
maxSum -= n;
int left = 0, right = 0;
int maxLeft = index, maxRight = n - index - 1;
while(maxSum > 0) {
res++;
int leftVal = Math.min(left++, maxLeft);
int rightVal = Math.min(right++, maxRight);
maxSum -= (1 + leftVal + rightVal);
if(leftVal == maxLeft && rightVal == maxRight) {
break;
}
}
if(maxSum > 0){
res = res + (maxSum/n);
}
return (maxSum<0) ? res-1 : res;
}
}
//Binary Search
class Solution {
public int maxValue(int n, int index, int maxSum) {
//Binary Search code
if(n == 1) return maxSum;
int left = 1, right = maxSum;
while(left < right) {
int mid = left + (right-left)/2;
long sum = calculateSumOfArray(mid, index, n);
if(sum <= maxSum) {
left = mid+1;
}
else {
right = mid;
}
}
return left-1;
}
//Calculate the Sum of array
private long calculateSumOfArray(int v, int i, int n){
long sum = 0;
if(v <= i){
int a = i+1-v;
sum+=summation(v-1) + a;
}
else {
int x = v-i;
sum+= summation(v-1) - summation(x-1);
}
if(v <= n-i){
int b = n-i-v;
sum+=summation(v-1) + b;
}
else {
int y = v-(n-i-1);
sum+= summation(v-1) - summation(y-1);
}
return sum+v;
}
//Utility method to apply summation formula
private long summation(int n) {
return (long)(n+1)*n/2;
}
}