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 7db3b34

Browse files
Update 1802. Maximum Value at a Given Index in a Bounded Array
1 parent bab7fef commit 7db3b34

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎1802. Maximum Value at a Given Index in a Bounded Array‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,59 @@ class Solution {
4343
return (maxSum<0) ? res-1 : res;
4444
}
4545
}
46+
47+
//Binary Search
48+
49+
class Solution {
50+
public int maxValue(int n, int index, int maxSum) {
51+
//Binary Search code
52+
if(n == 1) return maxSum;
53+
54+
int left = 1, right = maxSum;
55+
while(left < right) {
56+
int mid = left + (right-left)/2;
57+
long sum = calculateSumOfArray(mid, index, n);
58+
59+
if(sum <= maxSum) {
60+
left = mid+1;
61+
}
62+
else {
63+
right = mid;
64+
}
65+
}
66+
67+
return left-1;
68+
}
69+
70+
//Calculate the Sum of array
71+
private long calculateSumOfArray(int v, int i, int n){
72+
long sum = 0;
73+
if(v <= i){
74+
int a = i+1-v;
75+
sum+=summation(v-1) + a;
76+
}
77+
else {
78+
int x = v-i;
79+
sum+= summation(v-1) - summation(x-1);
80+
}
81+
82+
83+
if(v <= n-i){
84+
int b = n-i-v;
85+
sum+=summation(v-1) + b;
86+
}
87+
else {
88+
int y = v-(n-i-1);
89+
sum+= summation(v-1) - summation(y-1);
90+
}
91+
92+
return sum+v;
93+
94+
}
95+
96+
//Utility method to apply summation formula
97+
private long summation(int n) {
98+
return (long)(n+1)*n/2;
99+
}
100+
101+
}

0 commit comments

Comments
(0)

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