Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
选择最长的步数能保证最小的次数。
class Solution {
public:
int jump(int A[], int n) {
if(0==n)
return 0;
int cur=0,next=0,maxdistance=-1,count=0;//初始化老是出错
while(true)
{
if(next>=n-1) //写成maxdistance>=n-1老是[0]测试用例通不过
return count;
for(cur;cur<=next;++cur)
{
maxdistance=max(maxdistance,cur+A[cur]);//贪心算法,选择cur到next范围内最大的移动值,当前编号+当前位置可移动的最大值
}
cur=next; //下一步的新起点
next=maxdistance; //这一步能够走得最大值
count++;
}
}
};
题目2:
Say you have an array for which the ith 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.
找到最大利润,你只能进行一次交易
分析:
贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在 把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 1。
i--版本 用最大值
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() == 0)
return 0;
int ans;//最大差价
int maxPrices=prices[prices.size()-1];
for(int i=prices.size()-1;i>=0;i--)
{
maxPrices=max(maxPrices,prices[i]);//第i天之后,即i+1到第n天的最大利益maxPrices,即找曲线的最大值
ans=max(ans,maxPrices-prices[i]);//即i+1到第n天的最大利益maxPrices减去第i天,即第i天最大利益;ans为前面i天中利益最大的一天
}
return ans;
}
};
i++ 版本 用最小值
Say you have an array for which the ith 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).
题4:
Container With Most Water
描述
Given n non-negative integers a1; a2; :::; an, where each represents a point at coordinate (i; ai). n verti-
cal lines are drawn such that the two endpoints of line i is at (i; ai) and (i; 0). Find two lines, which together
with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container