Skip to content

Brute force approach #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions src/main/java/com/leetcode/arrays/BuySellStocks.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,19 @@ public class BuySellStocks {
* @param prices
* @return
*/
public static int maxProfit(int[] prices) {
int profit = 0;
int buyPrice = Integer.MAX_VALUE;

for (int i = 0; i < prices.length; i++) {
if (prices[i] < buyPrice) {
buyPrice = prices[i];
} else if (prices[i] - buyPrice > profit) {
profit = prices[i] - buyPrice;
public class Solution {
public int maxProfit(int prices[]) {
int maxprofit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > maxprofit)
maxprofit = profit;
}
}

return profit;
return maxprofit;
}
}

public static void main(String[] args) {

Expand Down
22 changes: 9 additions & 13 deletions src/main/java/com/leetcode/arrays/MajorityElement.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,19 @@ public class MajorityElement {
* @param nums
* @return
*/
public static int majorityElement(int[] nums) {
int count = 1;
int majElem = nums[0];
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;

for (int i = 1; i < nums.length; i++) {
if (count <= 0) {
majElem = nums[i];
count = 0;
}
if (majElem == nums[i]) {
count++;
} else {
count--;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}

return majElem;
return candidate;

}

public static void main(String[] args) {
Expand Down