Showing posts with label ad-hoc. Show all posts
Showing posts with label ad-hoc. Show all posts

Wednesday, May 13, 2020

LeetCode.402 Remove K Digits

1.Problem
https://leetcode.com/problems/remove-k-digits/

2.Idea
Keep deleting first x such is *xy*, x > y.

3.Source
 string removeKdigits(string num, int k) {  
      string ans = "";  
      for (int i = 0; i < num.size(); i++) {  
           while (ans.size() && ans.back() > num[i] && k) {  
                ans.pop_back();  
                k--;  
           }  
           if (ans.length() || num[i] != '0')  
                ans.push_back(num[i]);  
      }  
      while (ans.size() && k) {  
           ans.pop_back();  
           k--;  
      }  
      return ans == "" ? "0" : ans;  
 }  

Friday, April 10, 2020

Codeforces.1334C Circle of Monsters

1.Problem
https://codeforces.com/contest/1334/problem/C

2.Idea
Only start point takes a[i] shoots, and other places a[i] - b[i-1]. Check every places as start point.

3.Source
 int n, t;  
 ll a[300005], b[300005], ac[300005];  
 void solve()  
 {  
      ll sum = 0;  
      for (int i = 0; i < n; i++) {  
           ac[i] = max(0ll, a[i] - b[(i + n - 1) % n]);  
           sum += ac[i];  
      }  
      ll ans = 1ll << 60;  
      for (int i = 0; i < n; i++) {  
           ans = min(ans, sum - ac[i] + a[i]);  
      }  
      //cout << ans << endl;  
      printf("%lld\n", ans);  
 }  
 int main()  
 {  
      scanf("%d", &t);  
      while (t--) {  
           scanf("%d", &n);  
           for (int i = 0; i < n; i++) {  
                scanf("%lld%lld", &a[i], &b[i]);  
           }  
           solve();  
      }  
      return 0;  
 }  

Sunday, April 5, 2020

LeetCode 122. Best Time to Buy and Sell Stock II

1.Problem
https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3287/

2.Idea
Just keep adding positive diffs.

3.Source
 class Solution {  
 public:  
      int maxProfit(vector<int>& prices) {  
           int ans = 0;  
           for (int i = 1; i < prices.size(); i++) {  
                if (prices[i - 1] < prices[i]) {  
                     ans += (prices[i]- prices[i - 1]);  
                }  
           }  
           return ans;  
      }  
 };