Greedy Solutions
// leet 1221 ================================================================ class Solution { public int balancedStringSplit(String s) { int lCount = 0; int rCount = 0; int ans = 0; for(int i=0; i<s.length(); i++){ if(s.charAt(i) == 'L'){ lCount++; } else { rCount++; } if(lCount == rCount){ ans++; lCount = 0; rCount = 0; } } return ans; } } // leet 1663 =================================================================== class Solution { public String getSmallestString(int n, int k) { char[] str = new char[n]; for(int i=0; i<n; i++){ str[i] = 'a'; } k = k - n; for(int i=n-1; i>=0; i--){ if(k>25){ str[i] = 'z'; k -= 25; } else { str[i] = (char)(str[i] + k); k = 0; } } return String.valueOf(str); } } // leet 121 ===================================================================== class Solution { public int maxProfit(int[] prices) { int buyingPrice = Integer.MAX_VALUE; int profit = 0; for(int i=0; i<prices.length; i++){ if(buyingPrice > prices[i]){ buyingPrice = prices[i]; } else { profit = Math.max(profit, prices[i] - buyingPrice); } } return profit; } }
Leave a Comment