From 40833a2361a865b467aa7b10093887f931bda7e9 Mon Sep 17 00:00:00 2001 From: Amar Date: Thu, 1 Oct 2020 23:09:30 +0530 Subject: [PATCH 1/2] Brute force approach --- .../com/leetcode/arrays/BuySellStocks.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/leetcode/arrays/BuySellStocks.java b/src/main/java/com/leetcode/arrays/BuySellStocks.java index 4d4ba02b..81c99f75 100644 --- a/src/main/java/com/leetcode/arrays/BuySellStocks.java +++ b/src/main/java/com/leetcode/arrays/BuySellStocks.java @@ -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) { From 533dc1c7923be2b44ba52e815d4f216855641933 Mon Sep 17 00:00:00 2001 From: Amar Date: Thu, 1 Oct 2020 23:19:12 +0530 Subject: [PATCH 2/2] Using ternary operator --- .../com/leetcode/arrays/MajorityElement.java | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/leetcode/arrays/MajorityElement.java b/src/main/java/com/leetcode/arrays/MajorityElement.java index 2ccdd116..c38e3a70 100644 --- a/src/main/java/com/leetcode/arrays/MajorityElement.java +++ b/src/main/java/com/leetcode/arrays/MajorityElement.java @@ -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) {