funcmaxSubArray(nums []int)int { n := len(nums) ans := math.MinInt sum := 0 for i := 0; i < n; i++ { sum += nums[i] ans = max(ans, sum) if sum < 0 { sum = 0 } } return ans }
funcmaxProfit(prices []int)int { n := len(prices) ans := 0 for i := 1; i < n; i++ { if prices[i] > prices[i-1] { ans += prices[i] - prices[i-1] } } return ans }
funclargestSumAfterKNegations(nums []int, k int)int { n := len(nums) sort.Ints(nums)
for i := 0; i < n && nums[i] < 0 && k > 0; i, k = i+1, k-1 { nums[i] = -nums[i] } if k == 0 { return getSum(nums) } sort.Ints(nums) for k != 0 { nums[0] = -nums[0] k-- } return getSum(nums) }
funcgetSum(nums []int)int { ans := 0 for _, val := range nums { ans += val } return ans }
funccandy(ratings []int)int { n := len(ratings) need := make([]int, n) for i := 0; i < n; i++ { need[i] = 1 } for i := 1; i < n; i++ { if ratings[i] > ratings[i-1] { need[i] = need[i-1] + 1 } } for i := n - 2; i >= 0; i-- { if ratings[i] > ratings[i+1] { need[i] = max(need[i+1]+1, need[i]) } } ans := 0 for i := 0; i < n; i++ { ans += need[i] } return ans }
funcpartitionLabels(s string) []int { m := map[rune]int{} for idx, c := range s { m[c] = idx } left, right := 0, 0 ans := []int{} for idx, c := range s { right = max(right, m[c]) if idx == right { ans = append(ans, right-left+1) left = right + 1 } } return ans }
funcmonotoneIncreasingDigits(n int)int { s := []byte(strconv.Itoa(n)) i := 1 for i < len(s) && s[i] >= s[i-1] { i++ } if i < len(s) { for i > 0 && s[i] < s[i-1] { s[i-1]-- i-- } for i++; i < len(s); i++ { s[i] = '9' } } ans, _ := strconv.Atoi(string(s)) return ans }