Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1804.html

You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.

Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.

Note that abs(x) equals x if x >= 0, and -x otherwise.

 

Example 1:

Input: nums = [1,-1,1], limit = 3, goal = -4
Output: 2
Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.


Example 2:

Input: nums = [1,-10,9,1], limit = 100, goal = 0
Output: 1
 

Constraints:
  1 <= nums.length <= 105
  1 <= limit <= 106
  -limit <= nums[i] <= limit
  -109 <= goal <= 109
  • class Solution {
    public:
        int minElements(vector<int>& nums, int limit, int goal) {
            long sum = 0;
            for (int num : nums) {
                sum += num;
            }
            return (abs(goal - sum) + limit - 1) / limit;
        }
    };
    
    ############
    
    class Trie {
        private Trie[] children = new Trie[26];
        private int v;
        private int pv;
    
        public Trie() {
        }
    
        public void insert(String word) {
            Trie node = this;
            for (char c : word.toCharArray()) {
                c -= 'a';
                if (node.children[c] == null) {
                    node.children[c] = new Trie();
                }
                node = node.children[c];
                ++node.pv;
            }
            ++node.v;
        }
    
        public int countWordsEqualTo(String word) {
            Trie node = search(word);
            return node == null ? 0 : node.v;
        }
    
        public int countWordsStartingWith(String prefix) {
            Trie node = search(prefix);
            return node == null ? 0 : node.pv;
        }
    
        public void erase(String word) {
            Trie node = this;
            for (char c : word.toCharArray()) {
                c -= 'a';
                node = node.children[c];
                --node.pv;
            }
            --node.v;
        }
    
        private Trie search(String word) {
            Trie node = this;
            for (char c : word.toCharArray()) {
                c -= 'a';
                if (node.children[c] == null) {
                    return null;
                }
                node = node.children[c];
            }
            return node;
        }
    }
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie obj = new Trie();
     * obj.insert(word);
     * int param_2 = obj.countWordsEqualTo(word);
     * int param_3 = obj.countWordsStartingWith(prefix);
     * obj.erase(word);
     */
    
  • // OJ: https://leetcode.com/problems/implement-trie-ii-prefix-tree/
    // Time:
    //      Trie: O(1)
    //      insert, countWordsEqualTo, countWordsStartingWith, erase: O(W)
    // Space: O(1) extra space for all
    struct TrieNode {
        TrieNode *next[26] = {};
        int cnt = 0, end = 0;
    };
    class Trie {
        TrieNode root;
        TrieNode *findNode(string &s) {
            auto node = &root;
            for (char c : s) {
                if (!node->next[c - 'a'] || node->next[c - 'a']->cnt == 0) return nullptr;
                node = node->next[c - 'a'];
            }
            return node;
        }
    public:
        Trie() {}
        void insert(string s) {
            auto node = &root;
            for (char c : s) {
                if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
                node = node->next[c - 'a'];
                ++node->cnt;
            }
            ++node->end;
        }
        int countWordsEqualTo(string s) {
            auto node = findNode(s);
            return node ? node->end : 0;
        }
        int countWordsStartingWith(string s) {
            auto node = findNode(s);
            return node ? node->cnt : 0;
        }
        void erase(string s) {
            auto node = &root;
            for (char c : s) {
                node = node->next[c - 'a'];
                --node->cnt;
            }
            --node->end;
        }
    };
    
  • class Trie:
        def __init__(self):
            self.children = [None] * 26
            self.v = self.pv = 0
    
        def insert(self, word: str) -> None:
            node = self
            for c in word:
                idx = ord(c) - ord('a')
                if node.children[idx] is None:
                    node.children[idx] = Trie()
                node = node.children[idx]
                node.pv += 1
            node.v += 1
    
        def countWordsEqualTo(self, word: str) -> int:
            node = self.search(word)
            return 0 if node is None else node.v
    
        def countWordsStartingWith(self, prefix: str) -> int:
            node = self.search(prefix)
            return 0 if node is None else node.pv
    
        def erase(self, word: str) -> None:
            node = self
            for c in word:
                idx = ord(c) - ord('a')
                node = node.children[idx]
                node.pv -= 1
            node.v -= 1
    
        def search(self, word):
            node = self
            for c in word:
                idx = ord(c) - ord('a')
                if node.children[idx] is None:
                    return None
                node = node.children[idx]
            return node
    
    
    # Your Trie object will be instantiated and called as such:
    # obj = Trie()
    # obj.insert(word)
    # param_2 = obj.countWordsEqualTo(word)
    # param_3 = obj.countWordsStartingWith(prefix)
    # obj.erase(word)
    
    
    
  • type Trie struct {
    	children [26]*Trie
    	v        int
    	pv       int
    }
    
    func Constructor() (_ Trie) { return }
    
    func (this *Trie) Insert(word string) {
    	node := this
    	for _, c := range word {
    		c -= 'a'
    		if node.children[c] == nil {
    			node.children[c] = &Trie{}
    		}
    		node = node.children[c]
    		node.pv++
    	}
    	node.v++
    }
    
    func (this *Trie) CountWordsEqualTo(word string) int {
    	node := this.search(word)
    	if node == nil {
    		return 0
    	}
    	return node.v
    }
    
    func (this *Trie) CountWordsStartingWith(prefix string) int {
    	node := this.search(prefix)
    	if node == nil {
    		return 0
    	}
    	return node.pv
    }
    
    func (this *Trie) Erase(word string) {
    	node := this
    	for _, c := range word {
    		c -= 'a'
    		node = node.children[c]
    		node.pv--
    	}
    	node.v--
    }
    
    func (this *Trie) search(word string) *Trie {
    	node := this
    	for _, c := range word {
    		c -= 'a'
    		if node.children[c] == nil {
    			return nil
    		}
    		node = node.children[c]
    	}
    	return node
    }
    
    /**
     * Your Trie object will be instantiated and called as such:
     * obj := Constructor();
     * obj.Insert(word);
     * param_2 := obj.CountWordsEqualTo(word);
     * param_3 := obj.CountWordsStartingWith(prefix);
     * obj.Erase(word);
     */
    

All Problems

All Solutions