本文共 3258 字,大约阅读时间需要 10 分钟。
题目描述
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).思路
代码
public class Solution { public int maxProfit(int[] prices) { int len=prices.length; int maxPro=0; for(int i=1;iprices[i-1]){ maxPro+=prices[i]-prices[i-1]; } } return maxPro; }}
题目描述
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.思路
代码
import java.lang.Math;public class Solution { public int maxProfit(int[] prices) { int len=prices.length; if(prices==null||len==0){ return 0; } int min=prices[0]; int maxPro=0; for(int i=1;i
题目描述
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle[ [2], [3,4], [6,5,7], [4,1,8,3]]
The minimum path sum from top to bottom is11(i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.思路
import java.util.ArrayList;ArrayList.get(index);ArrayList.set(index,value);import java.lang.Math;Math.min(value1,value2);
代码
import java.lang.Math;import java.util.ArrayList;public class Solution { public int minimumTotal(ArrayList> triangle) { int len=triangle.size(); if(len==0){ return 0; } if(len==1){ int min=triangle.get(0).get(0); for(int i=0;i triangle.get(0).get(i)){ min=triangle.get(0).get(i); } } return min; } for(int i=len-2;i>=0;i--){ for(int j=0;j
题目描述
Given an index k, return the k th row of the Pascal's triangle.
For example, given k = 3,Return[1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space?思路
代码
import java.util.ArrayList;public class Solution { public ArrayListgetRow(int rowIndex) { ArrayList res=new ArrayList<>(); res.add(1); for(int i=0;i 0;j--){//注意要从后往前刷新,因为用的是一个动态数组,防止仍有用的数据被新值覆盖 res.set(j,res.get(j)+res.get(j- 1)); } res.add(1); } return res; }}
转载地址:http://nivwo.baihongyu.com/