-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday10.java
More file actions
100 lines (90 loc) · 2.28 KB
/
day10.java
File metadata and controls
100 lines (90 loc) · 2.28 KB
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
problem 1 : https://leetcode.com/problems/rearrange-array-elements-by-sign/description/
class Solution {
public int[] rearrangeArray(int[] nums) {
int n=nums.length,k=0,j=0;
int s=n/2;
int []pos=new int[s];
int []neg=new int[s];
for(int i=0;i<n;i++){
if(nums[i]>=0){
pos[k]=nums[i];
k++;
}
else{
neg[j]=nums[i];
j++;
}
}
k=0;
j=0;
for(int i=0;i<n;i++){
if(i%2==0){
nums[i]=pos[k];
k++;
}
else{
nums[i]=neg[j];
j++;
}
}
return nums;
}
}
TC:O(n)
SC:O(1)
Approach:we will make two seperate array for positive and for negative the add one by one to original array
problem 2:
import java.util.*;
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
int ind = -1;
for (int i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
ind = i;
break;
}
}
if (ind == -1) {
reverse(nums, 0, n - 1);
return;
}
for (int i = n - 1; i > ind; i--) {
if (nums[i] > nums[ind]) {
int tmp = nums[i];
nums[i] = nums[ind];
nums[ind] = tmp;
break;
}
}
reverse(nums, ind + 1, n - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
}
TC-O(n)
SC-O(1)
problem 3: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
}
TC:-O(n)
SC:-O(1)