Three

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

//Majority Elements

public int majorityElement(int[] nums) {


int counter = 0;
int candidate = nums[0];
for(int num : nums){
if(counter==0) candidate = num;
if(num == candidate) counter++;
else counter--;
}
return candidate;

Input: nums = [3,2,3]


Output: 3

----------------------------------------------------------------------
-----------
//valid Paranthesis

public boolean isValid(String s) {


int curSize = s.length();
while(s.length()>0){
s = s.replace("()", "");
s = s.replace("{}", "");
s = s.replace("[]", "");
if(s.length() != 0 && s.length() == curSize){
return false;
}
curSize = s.length();
}
return true;

Input: s = "()[]{}"
Output: true

----------------------------------------------------------------------
-----------
// Maximum Subarray

public int maxSubArray(int[] nums) {


int n = nums.length;
int curr = nums[0];
int sum = nums[0];
for (int i = 1; i < n; ++i) {
curr = Math.max(curr + nums[i], nums[i]);
sum = Math.max(sum, curr);
}
return sum;

Input: nums = [5,4,-1,7,8]


Output: 23

----------------------------------------------------------------------
-----------
//Climbing Stairs

public int climbStairs(int n) {


if(n == 0 || n == 1 || n == 2){return n;}
int[] mem = new int[n];
mem[0] = 1;
mem[1] = 2;
for(int i = 2; i < n; i++){
mem[i] = mem[i-1] + mem[i-2];
}
return mem[n-1];

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

----------------------------------------------------------------------
//count inversions

public static void main(String[]args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}

mergeSort(arr,0,n-1);
System.out.println(count);
}
public static int[] mergeSort(int[] arr, int start, int end){
if(start==end){
int[] b = new int[1];
b[0] = arr[start];
return b;
}

int mid = (start+end)/2;


int[] left = mergeSort(arr,start,mid);
int[] right = mergeSort(arr,mid+1,end);
int[] merged = merge(left, right);
return merged;
}
static int count = 0;
public static int[] merge(int[] left, int[] right){
int i=0, j=0, k=0;
int[] merged = new int[left.length+right.length];

while(i<left.length && j<right.length){


if(left[i]<=right[j])
{
merged[k++] = left[i++];
}
else
{
count += (left.length-i);
merged[k++] = right[j++];
}
}
while(i<left.length) merged[k++] = left[i++];
while(j<right.length) merged[k++] = right[j++];

return merged;
}
5
2 4 1 3 5
ans: 3
------------------------------------------------------------------

You might also like