摘要:題目要求代表對數組在位置上進行順時針的旋轉后生成的數組。暴力循環按照題目的要求,執行兩次循環即可以獲得的所有值,只需要從中比較最大值即可。
題目要求
Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. Calculate the maximum value of F(0), F(1), ..., F(n-1). Note: n is guaranteed to be less than 105. Example: A = [4, 3, 2, 6] F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
Bk代表對數組A在位置k上進行順時針的旋轉后生成的數組。F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1],要求返回獲得的最大的F(k)的值。
暴力循環按照題目的要求,執行兩次循環即可以獲得F(k)的所有值,只需要從中比較最大值即可。
public int maxRotateFunction(int[] A) { if(A == null || A.length == 0) return 0; int max = Integer.MIN_VALUE; for(int i = 0 ; i < A.length ; i++) { int value = 0; for(int j = 0 ; i < A.length ; j++) { value += j * A[(j+i)%A.length]; } max = Math.max(value, max); } return max; }數學思路
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1] F(k-1) = 0 * Bk-1[0] + 1 * Bk-1[1] + ... + (n-1) * Bk-1[n-1] F(k) = F(k-1) + sum - n*Bk[0] k = 0 Bk[0] = A[0] k = 1 Bk[0] = A[len-1] k = 2 Bk[0] = A[len-2] ...
public int maxRotateFunction(int[] A) { if(A == null || A.length == 0) return 0; int F = 0; int sum = 0; for(int i = 0 ; i想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注我的微信公眾號!將會不定期的發放福利哦~
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72428.html
摘要:問題描述解題思路使用數組自帶的方法和方法把數組最后一個取出來加入到頭部。使用數組的方法得到后個數,再用方法刪去后個數,最后用方法把得到的后個數添加到數組前面。 問題描述: 189.Rotate Array Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, t...
摘要:是數組各位累加和,是按照對數組乘積變換后的累加和,是題目所求的不同變換累加和的最大值。 Problem Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we ...
Problem Given an array, rotate the array to the right by k steps, where k is non-negative. Example Example 1: Input: [1,2,3,4,5,6,7] and k = 3Output: [5,6,7,1,2,3,4]Explanation:rotate 1 steps to the r...
Problem You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D mat...
LeetCode[48] Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up:Could you do this in-place? 復雜度O(N^2),O(1) 代碼 public void ro...
閱讀 1915·2023-04-26 01:56
閱讀 3112·2021-11-18 10:02
閱讀 3051·2021-09-09 11:35
閱讀 1284·2021-09-03 10:28
閱讀 3408·2019-08-29 18:36
閱讀 2846·2019-08-29 17:14
閱讀 833·2019-08-29 16:10
閱讀 1616·2019-08-26 13:45